JavaScript中[undefined×;2]和[undefined,undefined]之间的区别

JavaScript中[undefined×;2]和[undefined,undefined]之间的区别,javascript,arrays,undefined,Javascript,Arrays,Undefined,从 注意:这意味着7个空插槽的数组,而不是具有实际未定义值的插槽 这是什么意思 const foo = Array(2) undefined const bar = [undefined, undefined] undefined foo[0] === bar[0] true foo [undefined × 2] bar [undefined, undefined] 他们之间有什么区别?是否存在我只能使用其中一个而不能使用另一个的用例?foo有两个空插槽,没有填充任何内容(在console中

注意:这意味着7个空插槽的数组,而不是具有实际未定义值的插槽

这是什么意思

const foo = Array(2)
undefined
const bar = [undefined, undefined]
undefined
foo[0] === bar[0]
true
foo
[undefined × 2]
bar
[undefined, undefined]

他们之间有什么区别?是否存在我只能使用其中一个而不能使用另一个的用例?

foo
有两个空插槽,没有填充任何内容(在console中解析为
未定义的
)<代码>栏
中填充了
未定义的值

因此,例如
Array.prototype.map
被定义为仅在设置值时工作:

foo.map(() => console.log('test'))
// nothing

bar.map(() => console.log('test'))
// test
// test

foo
有两个空插槽没有填充任何内容(在控制台中解析为
未定义的
)<代码>栏
中填充了
未定义的值

因此,例如
Array.prototype.map
被定义为仅在设置值时工作:

foo.map(() => console.log('test'))
// nothing

bar.map(() => console.log('test'))
// test
// test

这是一个有趣的问题

当您执行
常量foo=Array(2)
;它创建的数组中没有任何内容,但长度为2。所以
foo.length==2
(true)


但是你知道,即使是
foo[0]==undefined
(true),实际上
foo[100]==undefined
(true),数组中实际上也没有任何内容。这就是为什么它不同于[undefined,undefined]

这是一个有趣的问题

当您执行
常量foo=Array(2)
;它创建的数组中没有任何内容,但长度为2。所以
foo.length==2
(true)


但是你知道,即使是
foo[0]==undefined
(true),实际上
foo[100]==undefined
(true),数组中实际上也没有任何内容。这就是为什么它不同于[undefined,undefined]

在foo中尝试执行
'0',而在bar中尝试执行
'0'
在foo中尝试执行
'0',而在bar中尝试执行
'0'