JavaScript数组中的空项目和undefined之间有什么区别? [英] What's the difference between empty items in a JavaScript array and undefined?
问题描述
考虑以下JavaScript代码(在节点REPL中):
Consider the following JavaScript code (in a node REPL):
> let a = new Array(10)
undefined
> a
[ <10 empty items> ]
> a.map(e => 1)
[ <10 empty items> ]
> let b = new Array(10).fill(undefined)
undefined
> b
[ undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined ]
> b.map(e => 1)
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
>
当我创建一个空数组时,我会得到空项目",它们的行为似乎与undefined
不同.有人可以解释有什么区别吗?
When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined
. Can someone explain what is the difference?
推荐答案
当我创建一个空数组时,我会得到空项目",似乎 行为与未定义的行为不同.有人可以解释什么是 有什么区别?
When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?
这是因为Array(10)
不会填充数组.但这只是将 length 属性设置为10
.因此,使用Array
构造函数创建的数组只是一个具有length属性的对象,而没有填充任何项.
That's because Array(10)
doesn't populate the array. But it just set the length property to 10
.So, the array created using Array
constructor is simply an object with a length property, but with no items populated.
这篇关于JavaScript数组中的空项目和undefined之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!