来自https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/of,
注意:这意味着一个包含7个空插槽的数组,而不是具有实际未定义值的插槽
这是什么意思?
const foo = Array(2)
undefined
const bar = [undefined, undefined]
undefined
foo[0] === bar[0]
true
foo
[undefined × 2]
bar
[undefined, undefined]
他们之间有什么区别?是否有任何用例我只能使用一个但不能使用另一个?
答案 0 :(得分:4)
foo
有两个没有填充任何内容的空插槽(在控制台中解析为undefined
)。 bar
填充了undefined
。
因此,例如Array.prototype.map
被定义为仅在设置值时起作用:
foo.map(() => console.log('test'))
// nothing
bar.map(() => console.log('test'))
// test
// test
答案 1 :(得分:1)
这是一个有趣的问题。
当你const foo = Array(2)
时;它会创建一个没有任何内容的数组,但长度为2.所以foo.length === 2
(真)。
但你甚至知道foo[0] === undefined
(真),行动foo[100] === undefined
(真),所以真的没有什么'在数组内部。这就是为什么它与[undefined,undefined]