我在Firefox-3.5.7/Firebug-1.5.3和Firefox-3.6.16/Firebug-1.6.2中观察到了这一点
当我开火萤火虫时:
var x = new Array(3)
console.log(x)
// [undefined, undefined, undefined]
var y = [undefined, undefined, undefined]
console.log(y)
// [undefined, undefined, undefined]
console.log( x.constructor == y.constructor) // true
console.log(
x.map(function() { return 0; })
)
// [undefined, undefined, undefined]
console.log(
y.map(function() { return 0; })
)
// [0, 0, 0]Run Code Online (Sandbox Code Playgroud)
这里发生了什么?这是一个错误,还是我误解了如何使用new Array(3)?
我试过这个
> Array(3)
[ <3 empty items> ]
> // and this joins up all the nothings
> Array(3).join('-')
'--'
> // but...
> Array(3).map((x) => 'a')
[ <3 empty items> ]
> // map doesn't work with the array of empty items!
Run Code Online (Sandbox Code Playgroud)
我以为我会得到与此相同的结果
> [undefined, undefined, undefined].map((x) => 'a')
[ 'a', 'a', 'a' ]
Run Code Online (Sandbox Code Playgroud)
那是怎么回事?
我试图在不使用 for 循环的情况下创建一个包含 3 个元素的数组,因此代码将是一行(或单个语句)。我想要做的是创建一个包含 3 个元素的数组,每个元素应该是 0 到 255 之间的随机数(将包括 0 和 255)。
let colors = new Array(3).map((v) => Math.floor(Math.random()*256));
Run Code Online (Sandbox Code Playgroud)
但是这段代码不起作用,我猜是因为每个元素都是未定义的,而 .map 数组属性无法映射未定义的元素。你有什么建议?