Home > Web Front-end > JS Tutorial > body text

Example of using the sort method of an array in JS_javascript skills

WBOY
Release: 2016-05-16 17:03:00
Original
1156 people have browsed it
Copy code The code is as follows:

var values=[0,1,5,10,15];
values.sort();
alert(values);// Output 0,1,10,15,5

This is because sort will call the toString method of each item For comparison, "10" is smaller than "5", so it is in front.
To sort values, you need to define a comparison function and pass the function into sort.
Copy code The code is as follows:

function compare(value1,value2){
if (value1return -1;
}else if(value1>value2){
return 1;
}else{
return 0;
}
}
var values=[0,1,5,10,15];
values.sort(compare);
alert(values);// Output 0,1,5,10,15

This is the forward direction. For the reverse direction, just exchange -1 and 1 in the comparison function and it will be ok.
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