A simple sorting example to understand closures as parameters

Source: Internet
Author: User
Using a simple sorting example, we can understand the sorting rules with parameters in sort and the closure as parameters for calculation.
 
Below is a piece of HTML content:
 
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">  
 
// $ Each is an iteration method. it traverses every element in the collection and uses it as a parameter to execute the closure operation function $ each (collection, closure) {var ret = []; // define the array for (VAR I = 0; I <collection. length; I ++) {// Add the result after the closure operation to the RET in the array set. push (closure (Collection [I]);} return ret;} // sort the table function sorttable (table, ID) {var rows = $ each (table. rows, function (x) {return X;}); If (ID = "ASC") // you can check whether the result is in ascending order {
// Sorting method with closure parameters, which can control the ascending or descending order. Rows. sort (function (a, B) {if (. childnodes [0]. innertext-0> B. childnodes [0]. innertext-0) {return 1;} else return-1;});} else if (ID = "DESC") {rows. sort (function (a, B) {if (. childnodes [0]. innertext-0> B. childnodes [0]. innertext-0) {return-1;} elsereturn 1 ;}) ;}// Add the sorted rows to the table $ each (rows, function (x) {X. parentelement. appendchild (x); Return X;}) ;}</SCRIPT> 

 

 
The corresponding output graph:
 
 

After you click Sort by ASC, it is displayed as follows:

Click sort by DESC and the output is:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.