gpt4 book ai didi

javascript - 对 float 数组进行排序

转载 作者:IT老高 更新时间:2023-10-28 22:00:25 27 4
gpt4 key购买 nike

我有一个 float 数组:

[ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ]

在数组上运行 sort() 后,我得到了这个:

[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]

请注意 5.8... 如何大于 JavaScript(Node)的 49.6...。这是为什么呢?

如何正确排序这些数字?

最佳答案

传入一个排序函数:

[….].sort(function(a,b) { return a - b;});

结果:

[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049] 

From MDN :

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order.

关于javascript - 对 float 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496898/

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