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

Notes on sorting arrays (Array) in js_javascript skills

WBOY
Release: 2016-05-16 17:02:52
Original
1089 people have browsed it

Just look at the code, the test results are also posted inside

Copy the code The code is as follows:

var arrDemo = new Array();

arrDemo[0] = 10;
arrDemo[1] = 50;
arrDemo[2] = 51;
arrDemo[3] = 100;

arrDemo.sort(); //After calling the sort method, the array itself will be changed, which affects the original array

alert(arrDemo);//10,100,50,51 By default, the sort method sorts by ascii alphabetical order, not by numerical order as we think

arrDemo.sort(function(a,b){return a>b?1:-1});//Sort from small to large

alert(arrDemo);//10,50,51,100

arrDemo.sort(function(a,b){return a

alert(arrDemo);//100,51,50,10


Conclusion:

1. After the array calls the sort method, it will affect itself (rather than generating a new array)

2. The sort() method sorts by characters by default, so when sorting a numeric array, don’t take it for granted that it will be sorted by numerical size!

3. To change the default sort behavior (that is, sort by characters), you can specify the sorting rule function (as shown in this example)

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!