Javascript 使用扩展运算符创建数组
下面是我在React书中找到的javascript箭头函数:Javascript 使用扩展运算符创建数组,javascript,arrays,syntax,Javascript,Arrays,Syntax,下面是我在React书中找到的javascript箭头函数: const createArray = (length) => [...Array(length)]; 为什么不直接返回一个新数组呢 const createArray = (length) => Array(length); 如果我使用任意一个定义记录createArray(7)的结果,我会得到相同的结果: (7) [undefined, undefined, undefined, undefined, undefi
const createArray = (length) => [...Array(length)];
为什么不直接返回一个新数组呢
const createArray = (length) => Array(length);
如果我使用任意一个定义记录createArray(7)的结果,我会得到相同的结果:
(7) [undefined, undefined, undefined, undefined, undefined, undefined, undefined]
与第二个定义相比,第一个定义实现了什么?创建数组的两种方法都不同。它们不会产生相同的结果 第二种创建数组的方法将创建一个稀疏数组,该数组只包含
length
own属性,没有索引属性。使用Object.getOwnPropertyNames()可以看到这一点
const arr=新数组(5);
log(Object.getOwnPropertyNames(arr))代码>数组(长度)
将创建一个稀疏数组-一个没有自己属性的数组(除了length
),不能使用数组迭代方法进行迭代:
const arr=新数组(7);
console.log(arr.hasOwnProperty('4'));
arr.forEach(()=>{
log('iteration');
});代码>我希望如果你想在这里看到它的例子
更多信息=>
数组(5)
=>[空x 5]
与[…数组(5)]
=>[未定义,未定义,未定义,未定义]
。不同之处在于初始化。在哪个环境中得到相同的结果?使用代码沙盒谢谢。这有帮助。我可以快速地将log语句更改为dump getOwnPropertyNames(),它显示了第一个方法提供了所有索引属性和length属性,而第二个方法只提供了length属性
const testArr = [
{ name: false, expected: false },
{ name: null, expected: false },
{ name: undefined, expected: false },
{ name: "", expected: false },
{ name: " \t\n", expected: false },
];
const createArray = (arr) => { return [...arr]}
console.log(createArray(testArr))