1. Function call without Apply
We often use Function.prototype.apply, pass an array as a parameter, and call a function with a set of parameters stored in the array
function doStuff(x,y,z){}
var args = [0,1,2]
//调用函数,传递args参数
doStuff.apply(null,args)
Using the spread operator, we can easily call the function while avoiding the use of apply, just add the spread operator to the array
doStuff(...args)
2. Merge arrays
arr.push(...arr2)//将arr2数组追加到数组arr的末尾
arr.unshift(...arr2)//将arr2追加到数组arr的开头
//整合两个数组,并且把某个数组放在另一个数组的任意特定位置上
var arr1 = [a,b]
var arr2 = [d,...arr1,e,f]
console.log(arr2) //[d,a,b,e,f]
3. Copy the array
过去是通过Array.prototype.slice来进行拷贝
//通过展开运算符进行拷贝
var arr = [1,2,3]
var arr2 = [...arr] //arr.slice()类似
arr2.push(4)
注意:数组的对象依然是引用值,所以不是任何东西都拷贝过去了
4. Convert arguments or NodeList to Array
Before Array.prototype.slicel was used to convert the array-like objects of NodeList and arguments into real arrays
This is easily achieved with the spread operator
[...document.querySelectorAll('div')]
甚至可以像数组一样获取参数
var myFun = function(...args){
//...
}
//也可以用Array.from达成相同的目的
5. Use the Math function
任何可接收任意数量的参数的函数,都可以使用展开运算符进行传参
let numbers = [2,3,5,1]
Math.min(...numbers) // 1
6. Deconstruct
let {x,y,...z} = {x:1,y:2,a:3,b:4}
console,log(x); //1
console.log(y); //2
console.log(z); //{a:3,b:4}
//将剩余的属性分配到展开运算符之后的z变量中