Yai*_*pro 6 javascript sorting
对对象数组进行排序(通过 number 类型的属性)不会返回类似于数字数组的排序结果。
为什么这样 ?
如何让它像数字一样排序?
演示:对数字数组进行排序
const sorted = [0, 5, 2, undefined, 3, 1, 4]
.sort((a, b) => a - b);
console.log(sorted);Run Code Online (Sandbox Code Playgroud)
演示:对对象数组进行排序
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);Run Code Online (Sandbox Code Playgroud)
我目前使用的是 Chrome 90。也许其他一些浏览器或引擎没有这个问题。告诉我。
Twi*_*her 10
根据规范:
- 如果 x 和 y 都未定义,则返回 +0。
- 如果 x 未定义,则返回 1。
- 如果 y 未定义,则返回 ?1。
- 如果参数 comparefn 不是未定义的,则
- 令 v 为 ToNumber(Call(comparefn, undefined, «x, y»))。
- ReturnIfAbrupt(v)。
- 如果 v 是 NaN,则返回 +0。
- 返回 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]在某些情况下,您的排序算法会产生 ,NaN因为undefined - someNum并且someNum - undefined两者都导致NaN。这意味着您的回调不一致,这意味着生成的排序顺序是实现定义的。
如果集合 S 中的所有值 a、b 和 c(可能是相同的值)满足以下所有要求,则函数 comparefn 是一组值 S 的一致比较函数: 符号 a <CF b 表示 comparefn (a, b) < 0; a =CF b 表示 comparefn(a, b) = 0(任一符号);a >CF b 表示 comparefn(a, b) > 0。
- 当给定一对特定的值 a 和 b 作为它的两个参数时,调用 comparefn(a, b) 总是返回相同的值 v。此外,Type(v) 是 Number,而 v 不是 NaN。请注意,这意味着对于给定的 a 和 b 对,a <CF b、a =CF b 和 a >CF b 中的一个将是正确的。
如果你NaN从.sort回调中返回,你的结果可以是任何东西:在这种情况下的行为没有被规范定义(尽管某些实现可能会产生一个更直观的结果......或不是)。因此,请确保永远不会返回NaN。在这种情况下,显式测试以查看.i被迭代的属性是否为undefined,并为其替换不同的值 - 可能是 Infinity 或 -Infinity。
const sanitize = val => val === undefined ? Infinity : val;
const notSorted = [
{i:0},
{i:5},
{i:2},
{i: undefined},
{i:3},
{i:1},
{i:4},
]
.sort((a, b) => sanitize(a.i) - sanitize(b.i))
.map(a => a.i);
console.log(notSorted);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |