gpt4 book ai didi

Javascript 控制台返回不正确的排序数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:21 27 4
gpt4 key购买 nike

我在 chrome 控制台中输入了以下代码。

var array = [25,7,8,41];
array.sort();

它返回 [25,41,7,8]。怎么回事?

最佳答案

The sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).

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.

如果您希望更正此问题,您可以编写一个比较函数作为传递给排序方法的第一个参数。引用文献中列出了一个!

编辑:张贴在这里以备将来使用...

var points = [40, 100, 1, 5, 25, 10];
function myFunction() {
points.sort(function(a, b){return a-b});
console.log(points);
}

Reference

关于Javascript 控制台返回不正确的排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40029157/

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