gpt4 book ai didi

javascript - Javascript 的原生排序方法是如何工作的?

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

[1, false, 10, "b", 3, "33", ":", "R", "^"].sort()

产生以下排序:

[1, 10, 3, "33", ":", "R", "^", "b", false]

谁能解释一下 sort 方法是如何工作的?我猜它一定是将所有内容都翻译成 ASCII。

当我这样做时情节变浓了

[1, false, 10, "b", 3, "33", ":", "R", "^"].sort(function(a,b) {return b-a})

输出如下:

[10, 1, false, "b", "33", 3, ":", "R", "^"]

有什么方法可以解决这种疯狂问题吗?

最佳答案

来自 MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.

和:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function.

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

关于javascript - Javascript 的原生排序方法是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185005/

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