Question on array.sort()
zzusunjs opened this issue · comments
Challenge Where do I belong has an issue.
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
.
Please describe how to reproduce this issue, and include links to screenshots if possible.
My code:
function where(arr, num) {
// 请把你的代码写在这里
arr.sort(function(a,b){
return a - b;
});
for(var i=0; i<arr.length; i++){
if(arr[i] >= num){
return i;
}
}
return arr.length;
}
where([5,3,20,3], 3);
Did I have to write a comparable function to sort a number array ?
I found that arr = [4, 2, 5]; arr.sort(function(a, b){return a - b});
works.
But Why arr = [4, 2, 5]; arr.sort();
won't work ?
Did I have to write a comparable function to sort a number array?
Short answer is no. But in order to minimize the possibility of unexpected result regarding to the sort
implementation of various JavaScript engines, it is stronly recommended that you do so.
I found that
arr = [4, 2, 5]; arr.sort(function(a, b){return a - b});
works.
No wonder.
But Why
arr = [4, 2, 5]; arr.sort();
won't work ?
It actually works (F.Y.I. I am on Chrome):
But obviously this wont' work, since the default sort
is based off ASCII:
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort