Home >Web Front-end >JS Tutorial >ES6 spread operator
The spread operator of ES6 can be said to be very useful. It provides great convenience in passing parameters to multi-parameter functions, replacing Apply, merging arrays, and assigning values with deconstruction.
The spread operator is three dots "...", which means each element in the object that implements the Iterator interface is iterated one by one and taken out to be used individually.
Look at this example:
console.log(...[3, 4, 5])
Result:
3 4 5
The call is actually:
console.log(3, 4, 5)
Merge arrays
You can use the spread operator to merge multiple arrays.
let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] let arr3 = [7, 8, 9] console.log([...arr1, ...arr2, ...arr3])
Result:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Function multi-parameter passing, replace Apply
First define the parameters as an array and define the function.
let arr4 = ['arg1', 'arg2', 'arg3', 'arg4'] let fun1 = (a1, a2, a3, a4) => { console.log( a1, a2, a3, a4) }
Before ES6, you had to pass array parameters to the function, or access the array elements according to the subscript to call the function. The disadvantage is the number of arrays and function parameters. The numbers are completely bound. If one number changes, it must be modified.
fun1(arr4[0], arr4[1], arr4[2], arr4[3])
Or just use Apply to call it. The result is of course no problem, and it was also the most used before ES6.
fun1.apply(null, arr4)
If you use the spread operator, it is convenient.
fun1(...arr4)
Result:
arg1 arg2 arg3 arg4
The call is simple and refreshing.
Used in conjunction with destructuring and assignment
, you can extract all elements after the first one from the array into another array.
let [var1, ...arr5] = [1, 2, 3, 4, 5, 6] console.log(var1) console.log(arr5)
Result:
1[ 2, 3, 4, 5, 6 ]
But be aware that when paired with deconstruction, expansion The operator can only be used on the last one, otherwise an error will be reported.
You can expand objects that implement the Iterator interface
For example, Map, Set, and arrays are implemented from the Iterator interface, but Object is not, so Extending Object will report an error.
Expand Set.
let set1 = new Set() set1.add(1) set1.add(2) set1.add(3) console.log(...set1)
Result:
1 2 3
Extended Map.
let map1 = new Map(); map1.set('k1', 1); map1.set('k2', 2); map1.set('k3', 3); console.log(...map1)
Result:
[ 'k1', 1 ] [ 'k2', 2 ] [ 'k3', 3 ]
Note that the expanded arrays According to the key-value pair structure of map, each array has two elements, one is key and the other is value.
If you extend Object, an error will be reported.
let obj1 = { p1: 1, p2: 2, p3: 3} console.log(...obj1)
The above is the detailed content of ES6 spread operator. For more information, please follow other related articles on the PHP Chinese website!