简体   繁体   中英

Creating array with spread operator

Here is a javascript arrow function I found in a React book:

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:

(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. You can see this using 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:

 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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