Array(len) 初始值设定项中的未定义值 [英] Undefined values in Array(len) initializer
问题描述
考虑:
var a = Array(3);
var b = [undefined,undefined,undefined];
a.map
和 b.map
产生不同结果的原因是什么?
What's the reason that a.map
and b.map
produce different results?
a.map(function(){ return 0; }); //produces -> [undefined,undefined,undefined]
b.map(function(){ return 0; }); //produces -> [0,0,0]
推荐答案
数组构造函数创建一个给定长度的数组.它不创建密钥.Array.prototype.map
's 回调函数只对列表中的元素执行.
也就是说,与键(整数)0 ≤ 相关联的所有值.我 长度.
The array constructor creates an array with the given length. It does not create the keys. Array.prototype.map
's callback function is only executed for the elements in the list.
That is, all values which are associated with a key (integer) 0 ≤ i < length.
Array(3)
有零个键,所以.map
的回调永远不会被触发.[void 0, void 0, void 0]
有三个键,为它们执行回调函数.
Array(3)
has zero keys, so.map
's callback is never triggered.[void 0, void 0, void 0]
has three keys, for which the callback function is executed.
Array(3).hasOwnProperty(0); // false
[void 0, void 0, void 0].hasOwnProperty(0); // true
规范及其polyfill 在MDN.在第 47 行,if (k in O) {
表明回调函数不会处理不存在的键.
The specification and its polyfill are mentioned at MDN. At line 47, if (k in O) {
shows that non-existant keys are not treated by the callback function.
这篇关于Array(len) 初始值设定项中的未定义值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!