有人可以向我解释一下为什么下面这段代码:
var points = [
99.1,
100,
99.9
];
console.log(points.sort());
... log()
这是未排序的数组:
[100, 99.1, 99.9]
sort()
之后,数组不应该是下面这个吗?
[100, 99.9, 99.1]
最佳答案
来自 w3schools:
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
您可以通过提供“比较函数”来解决此问题。
关于sort() 后 JavaScript 十进制数数组顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095226/