Sort of method of array in js
- 2020-03-30 02:04:49
- OfStack
Maybe you've been using sort of array in javascript.
Maybe you always believed it would give you the right result.
Or so I thought, until one day I saw the following code:
Perhaps the results were a bit unexpected. The results are as follows:
On closer inspection, the default sort method turns out to be not sort by shaping data, but string matching.
In other words, the 1 in 10 caused the error in the above code.
Of course, there are many solutions, and you can pass the callback function into the sort method.
So you get what you want.
Accidentally found, to record it, to prevent forgetting.
Maybe you always believed it would give you the right result.
Or so I thought, until one day I saw the following code:
[5,10,1].sort();
Perhaps the results were a bit unexpected. The results are as follows:
[1,10,5]
On closer inspection, the default sort method turns out to be not sort by shaping data, but string matching.
In other words, the 1 in 10 caused the error in the above code.
Of course, there are many solutions, and you can pass the callback function into the sort method.
[5,10,1].sort(function(x,y){
if(x>y) {return 1;
}else{
return -1
}
}
);
So you get what you want.
Accidentally found, to record it, to prevent forgetting.