简体   繁体   中英

Javascript ES6 Spread an array of undefined …[,,]

So after running this code

'use strict';
var myNewArray = Array(...[,,]);
console.log(myNewArray);

I get this

[undefined, undefined]

Can anyone explain me why I get only 2 undefined?

You have provided undefined values in the array [,,] .

The last item is not calculated because JavaScript considers it as a trailing comma. So if undefined is provided, it will be thrown away from the array.

     [ , , ]
   //     ^^ -> Here is nothing, so array currently has 2 items with `undefined`

If you will give a value after it, it will be added in the result array.

 const myNewArray = Array(...[,,1]); console.log(myNewArray); 

In addition to Suren's answer, you can clearly see in the specification that trailing elided elements are not counted into the length of the array.

Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

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