为什么不能映射'undefined'数组 [英] why can't map 'undefined' array

查看:146
本文介绍了为什么不能映射'undefined'数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As title say, why can't I map a array which contain undefined item?

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']

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

maybe the foolish question, but I really want to know the reason.

谢谢。

推荐答案

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


callback 仅对已分配值的数组的索引调用,包括 undefined 。它不会被调用缺少数组的元素(即,从未设置过的索引,已被删除或从未被赋值的索引)。

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).

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

It’s not working because elements haven’t been assigned a value.

如果你使用

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

然后它会起作用。

这篇关于为什么不能映射'undefined'数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆