我有一些 wtfjs
代码:
var a = [,];
alert(a.indexOf(a[0]));
a.indexOf(a[0])
返回 -1
。此示例中的要点是 uninitialized
和 undefined
值之间的区别:
a
包含一个未初始化的元素。
a[0]
返回 undefined
。
a
不包含 undefined
值。所以 a.indexOf(a[0]) === -1
是 true
。
但是我在哪里可以找到为什么 a[0]
返回 undefined
的解释?调用了什么内部方法?
附言Undefined
是 javascript 原始类型。 未初始化
表示没有任何javascript类型的值,但在javascript中没有这样的原始类型。
最佳答案
ES5 规范告诉我们以下 array initialisers :
Elided array elements are not defined.
请注意它们未定义。这与具有值 undefined
不同。正如您已经注意到的,省略的元素确实会影响数组的长度:
...the missing array element contributes to the length of the Array and increases the index of subsequent elements.
当您调用 indexOf
时在数组上,这是发生的步骤之一:
Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument ToString(k).
其中,k
是对应于数组索引的数字,O
是数组本身。由于未定义省略元素,因此数组没有相应索引的属性。
关于javascript - 当我通过索引获取数组元素值时,在 javascript 中调用什么内部方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21937727/