var fruit=[7,10,32,6,9,4];
document.write(fruit+'<br>');
fruit.sort(sortFun);
document.write(fruit);
function sortFun(ar1,ar2){
if(ar1>ar2){
return 1;
}else if(ar1<ar2){
return -1;
}else{
return 0;
}
}
How does this code arrange the array elements? Please give me a detailed explanation. Thank you.
To help you understand, you can try calling the sort method directly:
The return result is:
[10, 32, 4, 6, 7, 9]
而不是期待中的:
[ 4, 6, 7, 9, 10, 32]
Why is this happening?
Because this is the sort() method on the array prototype chain, which is
Array.prototype.sort()
.How to study this sort() method in depth:
1. You can go to the mdn document https://developer.mozilla.org...
2. You can go to "Javascript Advanced Programming", but the advanced design is not complete
3. The most violent way is to read the ECMA2015 specifications: http://www.ecma-international...
4. If you really feel it’s a headache, you can read the blog I wrote last year and repeat 1,2 , 3 steps: http://www.jianshu.com/p/b50a...
Hope it can help you...
You may need this article https://developer.mozilla.org...