我明白 map
is not called on undefined indexes在数组上,我很欣赏 undefined index 与显式分配“未定义”值的数组索引不同(是,不是吗?)。然而,应该如何区分数组中的空洞和 undefined
值?
下面的代码:
foo.js
var arr = [,,undefined,,,,3,,,4];
console.log("A hole the same as undefined? "+(arr[0]===undefined?"yes":"no"));
var _ignored = arr.map(function(x) {console.log("f called on ["+x+"]");});
...运行时产生:
$ node foo.js
A hole the same as undefined? yes
f called on [undefined]
f called on [3]
f called on [4]
...将 map
替换为 forEach
时会得到类似的结果。
最佳答案
in
运算符告诉您索引是否已实际分配给:
a = []
a[5] = window.foo
document.write(a[4] + "<br>")
document.write(a[5] + "<br>")
document.write((4 in a) + "<br>")
document.write((5 in a) + "<br>")
Javascript 数组实际上是具有特殊length
属性的对象,而数组索引只是属性名称(实际上,它们在内部甚至是字符串,而不是数字)。所以上面的定义等同于:
a = {
5: window.foo,
length: 6
}
因此,与键相关的所有对象功能(如 in
、hasOwnProperty
、Object.keys
)也适用于数组索引。
forEach
和其他迭代方法 work by iterating from 0 to length-1 and checking if n-th index is actually present in the argument ,他们不“知道”参数实际上是一个数组还是只是一个通用对象:
a = {1:'one', 5:'five', length:100};
[].forEach.call(a, function(x) {
document.write(x)
});
关于javascript - 数组中的空洞与未定义和映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517886/