javascript - 为什么不能映射 'undefined' 数组

标签 javascript

<分区>

如标题所说,为什么我不能映射包含undefined项的数组?

var foo = new Array(3);
// [ , , ]
var bar = [null, null, null];
// [null, null, null]

foo.map(function(val){return 'test'});
// [ , , ]
bar.map(function(val){return 'test'});
// ['test', 'test', 'test']

也许是愚蠢的问题,但我真的很想知道原因。

谢谢。

最佳答案

参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description :

callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

它不起作用,因为尚未为元素分配值。

如果你使用

foo[0] = undefined;
foo[1] = undefined;
foo[2] = undefined;

然后它会起作用。

关于javascript - 为什么不能映射 'undefined' 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407021/

相关文章:

javascript - 如何使用 jquery 选择具有特定 'alt' 属性的图像

javascript - "This"变成 "window"JavaScript

javascript - 将代码迁移到 html 和 javascript 后如何引用包

javascript - 从 Javascript 数组中删除项目并显示新数组

javascript - 同步等待 $.ajax 调用

javascript - 如何在缩放中显示 gridview 行

javascript - 取消选中时保留 float 图例标签复选框

javascript - ReplaceWith() 添加新行但不删除旧行?

javascript - 日期选择器未设置最大值和最小值

javascript - 使用 javascript 验证包含缩短版本的 YouTube 网址