被`new`创建的数组上的`map`的行为所困惑 [英] Confused by behavior of `map` on arrays created using `new`

查看:118
本文介绍了被`new`创建的数组上的`map`的行为所困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对映射的结果感到困惑,使用新建 c $ c创建的数组:

I am confused by the results of mapping over an array created with new:

function returnsFourteen() {
    return 14;
}

var a = new Array(4);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
a.map(returnsFourteen);
> [undefined x 4] in Chrome, [, , , ,] in Firefox

var b = [undefined, undefined, undefined, undefined];
> [undefined, undefined, undefined, undefined]
b.map(returnsFourteen);
> [14, 14, 14, 14]

我预计 a.map returnFourteen)返回 [14,14,14,14] (与相同b.map(returnsFourteen),因为根据阵列上的MDN页面

I expected a.map(returnsFourteen) to return [14, 14, 14, 14] (the same as b.map(returnsFourteen), because according to the MDN page on arrays:


如果传递给Array构造函数的唯一参数是一个整数
,介于0和2之间** 32-1(含),一个新的JavaScript数组被创建
与这个元素数量。

If the only argument passed to the Array constructor is an integer between 0 and 2**32-1 (inclusive), a new JavaScript array is created with that number of elements.

我解释说,这意味着 a 应该有4个元素。

I interpret that to mean that a should have 4 elements.

我在这里缺少什么?

推荐答案

当你创建一个这样的数组时:

When you create an array like so:

var arr1 = new Array( 4 );

你得到一个长度为 4 ,但是那个没有元素,这就是为什么 map 不会转换数组 - 数组没有要转换的元素。

you get an array that has a length of 4, but that has no elements. That's why map doesn't tranform the array - the array has no elements to be transformed.

另一方面,如果你这样做:

On the other hand, if you do:

var arr2 = [ undefined, undefined, undefined, undefined ];

你得到的数组也有一个长度 4 ,但是 具有4个元素。

you get and array that also has a length of 4, but that does have 4 elements.

注意没有元素之间的区别,并且元素的值为未定义。不幸的是,在这两种情况下,属性访问器表达式将评估为 undefined 值,因此:

Notice the difference between having no elements, and having elements which values are undefined. Unfortunately, the property accessor expression will evaluate to the undefined value in both cases, so:

arr1[0] // undefined
arr2[0] // undefined

但是,有一种区分这两个数组的方法:

However, there is a way to differentiate these two arrays:

'0' in arr1 // false
'0' in arr2 // true

这篇关于被`new`创建的数组上的`map`的行为所困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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