Array(n)和Array(n)之间的区别.fill? [英] Difference between Array(n) and Array(n).fill?
问题描述
我注意到,如果我这样做:
I've noticed that if I do:
Array(n).map(() => console.log('test'))
我什么都没打印。
但是如果我这样做:
Array(n).fill().map(() => console.log('test'))
我得到 test
打印出 n
次。
为什么会这样?如果我 Array(n)。length
我回来了 n
。
Why is this the case? If I do Array(n).length
I get back n
.
我在REPL中注意到 Array(5)
返回:
I notice in the REPL that Array(5)
returns:
[,,,,]
而数组(5).fill()
返回:
[未定义,未定义,未定义,未定义,未定义]
在这两种情况下, typeof
数组中的任何元素 === undefined
。
In both cases, typeof
any element in the array === undefined
.
那么,发生了什么?
推荐答案
map
仅对数组的已定义整数属性进行操作。 Array(n)
不设置整数属性,而 Array(n).fill()
则设置。 不存在的属性和现存属性之间存在差异,其值为 undefined
。
map
only operates on defined integer properties of an array. Array(n)
does not set integer properties, while Array(n).fill()
does. There's a difference between a property that doesn't exist and an extant property whose value is undefined
.
Array(n)
设置数组的 length
属性,但它没有设置任何属性。数组对象没有任何整数属性。
Array(n)
sets the length
property of the array, but it does not set any properties. The array object does not have any integer properties.
.fill
设置数组的所有整数属性零至少长度
。当您执行 Array(n)
时,设置新aray的 length
属性,然后 .fill()
定义并设置每个整数属性为 n-1
。由 Array(n).fill()
创建的数组的属性定义为 length - 1
。 (这些属性碰巧被设置为 undefined
,因为你没有将参数传递给 fill
,但他们这样做了存在。)
.fill
sets all of the integer properties for an array from zero up to one less than length
. When you do Array(n)
you set the length
property of the new aray, and then .fill()
defines and sets each integer property up to n-1
. The array created by Array(n).fill()
does have properties defined up to length - 1
. (The properties happen to be set to undefined
, because you didn't pass an argument to fill
, but they do exist.)
在实际条款中,如果你做 Object.keys(Array(4))$ c $,你可以看到差异c>(空数组)与
Object.keys(Array(4).fill())
(字符串列表0
到3
)。在第一种情况下,属性不存在;在第二种情况下,他们这样做。
In pracitcal terms, you can see the difference if you do Object.keys(Array(4))
(empty array) versus Object.keys(Array(4).fill())
(a list of strings "0"
to "3"
). In the first case, the properties don't exist; in the second case they do.
这篇关于Array(n)和Array(n)之间的区别.fill?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!