Home > Web Front-end > JS Tutorial > In-depth analysis of the use of js array Array sort method_javascript skills

In-depth analysis of the use of js array Array sort method_javascript skills

WBOY
Release: 2016-05-16 17:41:51
Original
1138 people have browsed it

The Array.sort() method in javascript is used to sort array items. By default, it is arranged in ascending order. The example code is as follows:

Copy code The code is as follows:

var arrA = [6,2,4,3,5,1];
arrA.sort();
document.writeln (arrA);
//The result is: 1,2,3,4,5,6

The sort() method can accept a method as a parameter. This method has two parameters. Represents the two array items in each sorting comparison.
When sort() sorts, this parameter will be executed every time two array items are compared, and the two compared array items will be passed to this function as parameters. When the function returns a value of 1, the order of the two array items is swapped, otherwise it is not swapped.
The example is as follows:
Copy code The code is as follows:

var arrA = [6, 2,4,3,5,1];
/**//*arrA.sort();
document.writeln(arrA);
*/
function desc(x,y)
...{
if (x > y)
return -1;
if (x < y)
return 1;
}
function asc(x,y)
...{
if (x > ; y)
return 1;
if (x < y)
return -1;
}
arrA.sort(desc); // sort by desc
document. writeln(arrA);
document.writeln("
");
arrA.sort(asc); //sort by asc
document.writeln(arrA);
// Output result:
6,5,4,3,2,1
1,2,3,4,5,6

In addition, you can put an unnamed function directly to the call to the sort() method. The following example is to arrange odd numbers in the front and even numbers in the back. The example is as follows:
Copy the code The code is as follows:

var arrA = [6,2,4,3,5,1];
arrA.sort( function(x, y) ...{
if (x % 2 == 0)
return 11;
if (x % 2 !=0)
return -1;
}
);
document.writeln(arrA);
/ /Output: 1,5,3,4,6,2
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template