扩大运算符含意扩大运算符(spread)是三个点(...),能够当作rest参数的逆运算,将数组转为用逗号分隔的参数序列rest是把传入的参数组合成一个数组扩大运算符是把数组分解成参数
console.log(...[1,2,3])//1,2,3console.log(1,...[2,3,4],5)//1,2,3,4,5[...document.querySelectorAll('div')]// [<div>, <div>, <div>]该运算符次要用于函数的调用,将一个数组,变为参数序列function push(array,...items){ array.push(...items)}function add(x,y){ return x+y}const numbers = [4,38]add(...numbers) //42...能够与失常的参数联合应用function f(v,w,x,y,z){ console.log(v,w,x,y,z) //-1 0 1 2 3}const args = [0,1]f(-1,...args,2,...[3]);...前面还能够搁置表达式var x = 1const arr = [ ...(x>0?['a']:[]), 'b',]console.log(arr) //['a','b']如果扩大运算符前面是一个空数组,则不产生任何成果。[...[], 1]// [1]只有函数调用时,扩大运算符才能够放在圆括号中(...[1, 2])// Uncaught SyntaxError: Unexpected numberconsole.log((...[1, 2]))// Uncaught SyntaxError: Unexpected numberconsole.log(...[1, 2])// 1 2下面三种状况,扩大运算符都放在圆括号外面,然而前两种状况会报错,因为扩大运算符所在的括号不是函数调用。代替apply办法es5:function f(x,y,z){ console.log(x,y,z) // 0 1 2}var args = [0,1,2];f.apply(null,args)因为f接管的参数不能为数组,为了不便,能够用apply办法来实现用数组的参数来传递,这是很多时候使用的一个小技巧罢了。而apply办法第一个参数,是要代替的对象。没有要代替的,用null,也是很天然的es6:function f(x,y,z){ console.log(x,y,z) // 0 1 2}var args = [0,1,2]f(...args)利用:Math.max// ES5 的写法Math.max.apply(null, [14, 3, 77])// ES6 的写法Math.max(...[14, 3, 77])// 等同于Math.max(14, 3, 77);将一个数组增加到另一个数组的尾部es5:var arr1 = [0, 1, 2];var arr2 = [3, 4, 5];Array.prototype.push.apply(arr1,arr2)console.log(arr1)//[0,1,2,3,4,5]push办法的参数不能是数组,所以只好通过apply办法变通应用push办法es6:let arr1 = [0, 1, 2];let arr2 = [3, 4, 5];arr1.push(...arr2);console.log(arr1)//[0,1,2,3,4,5]另一个例子// ES5new (Date.bind.apply(Date, [null, 2015, 1, 1]))// ES6new Date(...[2015, 1, 1]);bind.apply:
...