Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 45120  / 8 Years ago, fri, march 18, 2016, 12:00:00

I don't understand what the ... notation does exactly.



I tried a simple example with Babel to understand it (view the example), but it seems that:



ES6 syntax



let myArray = [1, 2, 3, ...18];

console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3


is the same as this ES5 syntax:



use strict;

function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}

var myArray = [1, 2, 3].concat(_toConsumableArray(18));

console.log(myArray); // [1, 2, 3]
console.log(myArray[4]); // undefined
console.log(myArray.length); // 3


BUT: What does this code do? Because the output (console.log) is the same as in this code (ES5):



var myArray = [1,2,3];

console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3


What does the ...18 notation mean?


More From » arrays

 Answers
5

The ...(spread operator) works by returning each value from index 0 to index length-1:



As example:



[...'18'] // returns ['1', '8']


which would be the same as:



['18'[0], '18'[1]]





Now, to get an array from 1 to 18, you can do this:



[...Array(19).keys()].slice(1)


Or this with map:



[...Array(18)].map(_=>i++,i=1)


Hope it helps.


[#62886] Wednesday, March 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;