javascript - 数组中的空洞与未定义和映射函数

标签 javascript arrays

我明白 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
}

因此,与键相关的所有对象功能(如 inhasOwnPropertyObject.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/

相关文章:

javascript - WebStorm 2016.1.3 React 属性错误自动完成

javascript - reddit 是如何在弹出登录表单时让整个背景变黑的?

java - 在java中比较2个字符串数组并打印两个数组中相同的元素

javascript - 嵌套 for 循环和多维数组

python - N 维数组使用示例

javascript - 简化下拉列表的js

php - 如何创建下载计数器

java - 在 GWT 中将 JavaScriptObject 转换为 Java 对象失败

php - 在 func_get_args() 中有变量名

python - 从第三个数组中的两个数组中有效地获取每对元素的最小值