javascript - JS - 为什么 array.sort() 不会为对象和数字返回相同的结果?

标签 javascript sorting

对对象数组进行排序(按数字类型的属性)不会像数字数组那样返回排序结果。
为什么这样 ?
如何使它像数字一样排序?
演示:对数字数组进行排序

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.ib.iundefined , 它返回 NaN (不是数字)。
随着回调返回 NaN对于每个 undefined属性,它们被认为与其他所有项目相同。这会导致不稳定的行为,这取决于 Array.prototype.sort() 的实际算法。在 JavaScript 引擎中。
以下是某些浏览器的问题示例的返回值:
  • IE 11:[0, 1, 2, 5, undefined, 3, 4]
  • 边缘 Chrome 90:[0, 1, 2, 3, 5, undefined, 4]
  • 火狐 88:[0, 2, 5, undefined, 1, 3, 4]
  • 关于javascript - JS - 为什么 array.sort() 不会为对象和数字返回相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67420536/

    相关文章:

    javascript - meteor 0.9.1.1 : how to use a spinner

    javascript - 具有多种功能的backbone js模型解析函数

    javascript - 遇到这个基本的 while 循环硬件问题

    mysql 使用带有算术表达式的 select

    在C中按字母顺序比较字符串

    sorting - `take n (sort xs)` ("sorted prefix") 问题的内存高效算法

    javascript - 模拟不同选择器的点击事件

    javascript - JSUnit 中的 assertEquals() 实际上做了什么?

    r - 自然排序以按列名称对数据框的列进行排序

    php - 按到数字的距离对数组进行排序