1. 定义
扩展运算符(...), 将一个数组转为用逗号分隔的参数序列
- var arr = [1,2,3,4]
- console.log(...arr) //1 2 3 4
2. 常用位置
作为函数参数调用
- function add (a, b){
- return a+b
- }
- var arg = [12, 45]
- add(...arg)
某些情况代替 apply
- function applyFn(){
- }
- applyFn.apply(null,[1,2,3])
- // 等价于
- applyFn(...[1,2,3])
- Math.max.apply({
- },[1,2,3])
- // 等价于
- Math.max(...[1,2,3])
- var a = [1,2]
- var b = [3,4]
- Array.prototype.push.apply(a,b)
- console.log(a) // 1,2,3,4
- // 等价于
- a.push(...b)
3. 合并数组
- var a = [1,2]
- var b = [3,4]
- var c = [...a, ...b]
- // c = [1,2,3,4]
4. 与解构赋值结合
- const [a , ...b] = [1,2,3]
- // a=1 b=[2,3]
- const [a, ...b] = []
- // a=undefined b=[]
- const [a, ...b] = ['abc']
- // a ='abc' b=[]
扩展运算符只能放在最后一位, 放在前面报错 [...a,b] 这样报错
5. 字符串
- [...'abc']
- // ['a' , 'b' , 'c']
6. dom 节点获取
- var nodes = document.querySelectorAll('div')
- var arr = [...nodes]
- // 这样得到的 arr , 就是 div 节点的数组
来源: http://www.jianshu.com/p/da116382adc8