gpt4 book ai didi

javascript - 数值数组排序()

转载 作者:可可西里 更新时间:2023-11-01 02:43:19 24 4
gpt4 key购买 nike

《Learning PHP, MySql and Javascript by. Robin Nixon》这本书的这一部分有错吗?

numbers = [7, 23, 6, 74];

numbers.sort(function(a,b){return a - b});

输出为 6,7,23,74

书上说:

If the anonymous function inside sort() returns a value greater than zero, the sort assumes a comes before b.

If the anonymous function inside sort() return a value less than zero, the sort assumes b comes before a.

The sort runs this function across all the values in the array to determine their order.

这是错的吗?因为....

a 这里是7
b 这里是 23

7 - 23 = -16//一个小于零的数字。书上说 b 应该在 a 之前。

所以最终输出应该是74, 23, 7, 6

最佳答案

看来是错的。来自 MDN :

If compareFunction(a, b) is less than 0, sort a to a lower index than b.

(“较低的索引”在这种情况下意味着 a 在 b 之前)

关于javascript - 数值数组排序(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367697/

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