Spread Operator
Version ≥ 6 With ES6, you can use spreads to separate individual elements into a comma-separated syntax. It is equivalent to
use of split()
method.
let arr1 = [1, 2, 3, ...[4, 5, 6]]; // [1, 2, 3, 4, 5, 6]
// in ES < 6, the operations above are equivalent to
let arr2 = [1, 2, 3];
arr2.push(4, 5, 6);
console.log(arr2);
// expected output: [1, 2, 3, 4, 5, 6]
The spread operator also acts upon strings, separating each individual character into a new string element. Therefore, using an array function for converting these into integers, the array created above is equivalent to the one below:
let arr = [1, 2, 3, ...[..."456"].map(x=>parseInt(x))]; // [1, 2, 3, 4, 5, 6]
var stringArr = [..."456"];
console.log("stringArr :");
console.log(stringArr);
// expected output: ["4", "5", "6"]
let arr = [1, 2, 3, ...[..."456"].map((x) => parseInt(x))];
console.log("arr1");
console.log(arr);
// expected output: [1, 2, 3, 4, 5, 6]