简体   繁体   English

使用扩展运算符创建数组

[英]Creating array with spread operator

Here is a javascript arrow function I found in a React book:这是我在 React 书中找到的 javascript 箭头 function:

const createArray = (length) => [...Array(length)];

Why not simply return a new array?为什么不简单地返回一个新数组?

const createArray = (length) => Array(length);

If I log the result of createArray(7) with either of the definitions, I get the same result:如果我使用任一定义记录 createArray(7) 的结果,我会得到相同的结果:

(7) [undefined, undefined, undefined, undefined, undefined, undefined, undefined]

What does the first definition achieve as compared to the second one?与第二个定义相比,第一个定义实现了什么?

Both ways of creating an array are different .两种创建数组的方式都不同 They do not produce the same result.它们不会产生相同的结果。

Second way of creating an array will create a sparse array with only length own property and no index properties.创建数组的第二种方法将创建一个只有length自己的属性而没有索引属性的稀疏数组。 You can see this using Object.getOwnPropertyNames()您可以使用Object.getOwnPropertyNames()看到这一点

 const arr = new Array(5); console.log(Object.getOwnPropertyNames(arr));

Using the spread syntax will create an array will index properties as shown in the following code example:使用扩展语法将创建一个数组,并将索引属性,如以下代码示例所示:

 const arr = [...new Array(5)]; console.log(Object.getOwnPropertyNames(arr));

Array(length); will create a sparse array - one with no own-properties (except length ), which cannot be iterated over with the array iteration methods:将创建一个稀疏数组- 一个没有自己的属性(除了length ),它不能用数组迭代方法迭代:

 const arr = new Array(7); console.log(arr.hasOwnProperty('4')); arr.forEach(() => { console.log('iteration'); });

In contrast, utilizing spread syntax will populate the new array properly:相反,使用扩展语法将正确填充新数组:

 const arr = [...new Array(7)]; console.log(arr.hasOwnProperty('4')); arr.forEach(() => { console.log('iteration'); });

i hope if you want its example here.我希望如果你想要它的例子在这里。

More Information = > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax更多信息 = > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM