通过map`的'行为对使用`new`创建的阵列困惑 [英] Confused by behavior of `map` on arrays created using `new`
问题描述
我对地图
平的结果与上创建一个数组混淆新
:
I am confused by the results of map
ping 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(returnsFourteen)
返回 [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构造函数的唯一参数是一个整数
2 ** 32-1(含)之间的0,并创建一个新的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.
我间preT这意味着 A
应该有4个元素。
I interpret that to mean that a
should have 4 elements.
我是什么在这里失踪?
推荐答案
在创建这样一个数组:
var arr1 = new Array( 4 );
你有 4
的长度的数组,但拥有的没有的元素。这就是为什么地图
不转换阵列 - 数组有没有被转化元素
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.
注意,无元素,具有元件,其值未定义
之间的差异。不幸的是,属性访问前pression将评估在两种情况下,未定义
价值,所以:
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
这篇关于通过map`的'行为对使用`new`创建的阵列困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!