对对象数组进行排序(按数字类型的属性)不会像数字数组那样返回排序结果。
为什么这样 ?
如何使它像数字一样排序?
演示:对数字数组进行排序
const sorted = [0, 5, 2, undefined, 3, 1, 4]
.sort((a, b) => a - b);
console.log(sorted);
演示:对对象数组进行排序
const notSorted = [
{i:0},
{i:5},
{i:2},
{i: undefined},
{i:3},
{i:1},
{i:4},
]
.sort((a, b) => a.i - b.i)
.map(a => a.i);
console.log(notSorted);
我目前使用的是 Chrome 90。也许其他一些浏览器或引擎没有这个问题。告诉我。
最佳答案
根据spec :
- If x and y are both undefined, return +0.
- If x is undefined, return 1.
- If y is undefined, return −1.
- If the argument comparefn is not undefined, then
- Let v be ToNumber(Call(comparefn, undefined, «x, y»)).
- ReturnIfAbrupt(v).
- If v is NaN, return +0.
- Return v.
这就解释了为什么它在第一种情况下起作用,因为排序的值没有包含在对象中。在第二种情况下,值不是
undefined
(只有属性)所以原生 undefined
处理Array.prototype.sort()
不接管,这意味着回调正在执行,即使 a.i
或 b.i
是 undefined
, 它返回 NaN
(不是数字)。随着回调返回
NaN
对于每个 undefined
属性,它们被认为与其他所有项目相同。这会导致不稳定的行为,这取决于 Array.prototype.sort()
的实际算法。在 JavaScript 引擎中。以下是某些浏览器的问题示例的返回值:
[0, 1, 2, 5, undefined, 3, 4]
[0, 1, 2, 3, 5, undefined, 4]
[0, 2, 5, undefined, 1, 3, 4]
关于javascript - JS - 为什么 array.sort() 不会为对象和数字返回相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67420536/