Home  >  Article  >  Web Front-end  >  Notes on sorting arrays (Array) in js_javascript skills

Notes on sorting arrays (Array) in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:02:521092browse

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)

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