本文介绍了为什么我不能将新的Array(3)映射到新值的数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解背后的为什么

var a = new Array(3);
var b = a.map(function () {
  return 'b';
});

结果

a: [,,]

b: [,,]

当我希望b导致 ['b','b','b']

在进一步调查中,我发现如果我要做 a.push('a' ),我有 [,,,'a']

In further investigation, I discovered that if i were to do a.push('a'), I'd have [, , , 'a'].

在地图功能之后, b 将变为 [,,,'b' ]

And after the map function, b would become [, , , 'b'].

这里发生了什么?为什么这些分配的单元格的行为与初始化不同?我最初期望这样做,如果它是一个数组文字, [undefined,undefined,undefined] .map(fn)

What's going on here? Why do these allocated cells behave differently from the initialization? I was originally expecting this to act as it would if it was an array literal, [undefined, undefined, undefined].map(fn)

推荐答案

不会为未定义其值的索引调用回调。

Array.map() does not invoke the callback for indexes whose values aren't defined.

来自MDN文档:

这篇关于为什么我不能将新的Array(3)映射到新值的数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:34
查看更多