semi-xi / blog

blog
4 stars 1 forks source link

数组sort有无回调函数的差异 #24

Open semi-xi opened 4 years ago

semi-xi commented 4 years ago

如果没有指明回调函数 ,那么元素会按照转换为的字符串的诸个字符的Unicode位点进行排序。例如 "Banana" 会被排列到 "cherry" 之前。 当数字按由小到大排序时,9 出现在 80 之前,但因为没有指明回调函数,比较的数字会先被转换为字符串,所以在Unicode顺序上 "80" 要比 "9" 要靠前。

无回调
[0,3,2,4,1,9,80].sort() // [0, 1, 2, 3, 4, 80, 9]
有回调
[0,3,2,4,1,9,80].sort(()=>{}) //[0, 3, 2, 4, 1, 9, 80]