我尝试使用排序函数来排列项目,以便找到数字数组中的最大元素。 在 Chrome 中,检查元素并打开控制台。
>>var a = [1000, 1001, 857, 1]
>>undefined
>>a.sort()
>>(4) [1, 1000, 1001, 857] // no patern found.
为什么这些数字没有像其他案例那样正确排序:
>>var b = [13, 27, 18, 26];
>>undefined
>>b.sort()
>>(4) [13, 18, 26, 27] // here the numbers are in ascending order.
最佳答案
这是因为默认排序顺序将数组元素视为文本,而不是数字。
The default sort order is according to string Unicode code points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
关于javascript - JavaScript 中的排序函数在某些情况下无法给出正确的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295763/