Home >Web Front-end >JS Tutorial >Example of using the sort method of an array in JS_javascript skills

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

WBOY
WBOYOriginal
2016-05-16 17:03:001175browse
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.
Statement:
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