Home > Web Front-end > JS Tutorial > Introduction to the use of sort() method of array in js_javascript skills

Introduction to the use of sort() method of array in js_javascript skills

WBOY
Release: 2016-05-16 16:58:59
Original
1068 people have browsed it

Maybe you have been using array sort in javascript.

Maybe you have always believed that it will give you the correct result.

At least I used to think so, until one day, I saw the following code:

Copy code The code is as follows:

[5,10,1].sort();

Perhaps the result is a bit unexpected. The result is as follows:
Copy code The code is as follows:

[1,10,5]

After careful investigation, I found that the default sort method does not sort by integer data, but uses string matching.

In other words, it is the 1 in 10 that causes the error in the above code.

Of course, there are many solutions. You can pass the callback function into the sort method.
Copy code The code is as follows:

[5,10,1].sort(function( x,y){
if(x>y) {return 1;
}else{
return -1
}
}
);

This way you will get the results you expected.

If you find something by accident, record it to prevent forgetting.
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