jjzjj

JavaScript map : Why does this not work?

coder 2024-05-05 原文

<分区>

我试图使用 map 生成一些随机数据。令我惊讶的是,我无法弄清楚为什么这段代码不起作用。

考虑以下按预期工作的代码段:

const empty = [undefined, undefined];
const rand = empty.map(item => Math.random());

Output: [0.4774752874308936, 0.8482276976659398]

我试图简化一点并执行以下操作

const rand = Array(2).map(item => Math.random())

Output: [undefined × 2]

我不明白为什么会这样。显然,Array(n) 和 [] 生成的数组都是典型的数组,并且具有所有原型(prototype)方法。

Array(2) instanceof Array
true

[undefined, undefined] instanceof Array
true

Array.isArray(Array(2))
true

Array.isArray([undefined, undefined])
true

有人能指出我哪里出错了吗?

有关JavaScript map : Why does this not work?的更多相关文章

随机推荐