gpt4 book ai didi

sort() 后 JavaScript 十进制数数组顺序不正确

转载 作者:行者123 更新时间:2023-12-03 11:01:00 26 4
gpt4 key购买 nike

有人可以向我解释一下为什么下面这段代码:

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.

您可以通过提供“比较函数”来解决此问题。

http://www.w3schools.com/jsref/jsref_sort.asp

关于sort() 后 JavaScript 十进制数数组顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com