Home >Web Front-end >JS Tutorial >Analysis of array sort and reverse usage in Javascript_javascript skills

Analysis of array sort and reverse usage in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:051146browse

The examples in this article describe the usage of array sort and reverse in Javascript. Share it with everyone for your reference. The specific analysis is as follows:

The

sort() method is used to sort the elements of an array.

reverse() reverses the order of the elements in the array

First let’s try the following code:

Copy code The code is as follows:
var values ​​= [1, 0, 5, 15, 10];
values.reverse();
console.log(values);

What will the output be:
[ 10, 15, 5, 0, 1 ]

reverse() is simply to reverse the array, so the next thing I want to complain about is sort()

Copy code The code is as follows:
var values ​​= [1, 0, 5, 15, 10];
values.sort();
console.log(values);

The output result of this function is actually:
[ 0, 1, 10, 15, 5 ]

What’s going on?

Actually, will use toString() transformation inside the sort() function, and String comparison is through ASCII, so if we need to sort, it is better to write a sort() ourselves.

Copy code The code is as follows:
var values ​​= [1, 0, 5, 15, 10];
function compare(value1, value2) {
If (value1 < value2) {
         return -1;
} else if (value1 > value2) {
Return 1;
} else {
         return 0;
}
}
values.sort(compare);
console.log(values);

If you swap -1 and 1, you can sort in reverse order.

Current output:
[ 0, 1, 5, 10, 15 ]

A simpler way to write it is to use return value2 - value1;

inside compare()

I hope this article will be helpful to everyone’s JavaScript programming design.

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