为什么我不能将新的Array(3)映射到新值的数组中? [英] Why can't I map new Array(3) into an array of new values?

查看:96
本文介绍了为什么我不能将新的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() 不会为未定义其值的索引调用回调。

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

来自MDN文档:


map为每个调用一次提供的回调函数
数组中的元素按顺序,并从结果中构造一个新数组。仅对已分配值的数组的索引调用callback
;
未调用未定义的索引,已删除
的索引或从未分配过的值。

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values.

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

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