【问题标题】:What are "non-existent property values" in ECMA spec for ARRAY:SORT什么是 ARRAY:SORT 的 ECMA 规范中的“不存在的属性值”
【发布时间】:2022-07-19 14:16:42
【问题描述】:

在this question 的答案中(否则我可以完全理解/等等),有一个非常奇怪的:

根据规范,15.4.4.11:

因为不存在的属性值总是比较大于 未定义的属性值,并且未定义总是比较大于 任何其他值,未定义的属性值总是排序到末尾 结果,后跟不存在的属性值。

我检查了latest version available now,它是sort 规范末尾的“注释1”,它与编写2011 年的答案时基本相同。

关于undefined property values always sort to the end of the result, followed by non-existent property values——怎么可能?什么是“不存在的属性值”(*)?如果我们写a.foo和a没有这样的属性,我们会得到undefined,那么如何区分呢?

sort 要么在没有任何参数的情况下调用,要么使用比较器样式的函数调用,在后一种情况下,它是我们的函数,我们必须读取不存在的属性并获取 undefined。 .sort 无法检查对象的键,以便我们决定检查的对象是否具有属性(与某些下划线/lodash 帮助器相反,您定义“路径”,例如 pluck 或 @987654333 @)。我只是根本不明白我们如何触发这种“不存在的属性值”案例。

(*) 我发现了一些看起来像是这个术语的定义here:

不存在的属性是在不可扩展的目标上不作为自己的属性存在的属性。 (...) 如果目标不可扩展且 P 不存在,那么所有未来 在目标上调用 [[GetOwnProperty]] (P) 必须将 P 描述为 不存在(即 [[GetOwnProperty]] (P) 必须返回 undefined)。

这个 must-describe-as-nonexistent 和 must-return-undefined 似乎支持了我的怀疑。

我还注意到SortIndexedProperties(用于定义sort)的伪代码实际上包含3.b. Let kPresent be ? HasProperty(obj, Pk). 之类的位。那么,sort 规范中的 non-existent property 部分可能是为了涵盖某些情况,例如数组被比较器函数变异并且某些键被从中删除?

【问题讨论】:

    标签: javascript language-lawyer


    【解决方案1】:

    仅当数组稀疏时,才会“包含”数组上不存在的属性。下面是一个例子,看看 cmets:

    const arr = []; // 0-length array
    arr[2] = 'foo'; // Turns into 3-length array. Does not have own properties 0 or 1
    arr.sort();
    
    console.log(arr[0]); // Sort result includes a value from defined property
    console.log(arr.hasOwnProperty(1)); // But not from the sparse elements
    console.log(arr.length); // But the array will have the same length as originally

    如您所见,原始稀疏数组中不存在的属性被“排序”到数组的末尾,并且在生成的排序数组中也不存在,除了.length排序后的数组。它开始是一个长度为 3 且只有一个自有属性的数组,最终是一个长度为 3 且只有一个自有属性的数组(但该自有属性位于不同的索引处)。

    如果我们写 a.foo 而 a 没有这样的属性,我们会得到 undefined,那么如何区分呢?

    相当于.hasOwnProperty检查:

    const obj1 = {};
    const obj2 = { foo: undefined };
    console.log(obj1.hasOwnProperty('foo'));
    console.log(obj2.hasOwnProperty('foo'));
    
    const arr1 = ['abc'];
    const arr2 = [, 'def']; // sparse array
    console.log(arr1.hasOwnProperty(0));
    console.log(arr2.hasOwnProperty(0));

    解决所有这些问题的最佳方法 - 从一开始就不要使用稀疏数组,它们太混乱了。

    【讨论】:

      猜你喜欢
      • 2019-07-07
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多