ES6引入rest参数( 形式为“...变量名”) , 用于获取函数的多余参数, 这样就不须要使用arguments对象了。 rest参数搭配的变量是一个数组, 该变量将多余的参数放入数组中。数组
function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10
1.rest参数中的变量表明一个数组, 因此数组特有的方法均可以用于这个变量。 下面是一个利用rest参数改写数组push方法的例子。app
function push(array, ...items) { items.forEach(function(item) { array.push(item); }); return array } var a = []; push(a, 1, 2, 3) //[1,2,3]
扩展运算符( spread) 是三个点( ...) 。 它比如rest参数的逆运算, 将一个数组转为用逗号分隔的参数序列。函数
console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5 [...document.querySelectorAll('div')] // [<div>, <div>, <div>]
1.扩展运算符将数组变为参数序列rest
function add(x,y){ return x + y } var numbers = [4,28]; add(...numbers) //42
2.替代数组的apply 方法,因为扩展运算符能够展开数组, 因此再也不须要apply方法, 将数组转为函数的参数了。code
// ES5的写法 function f(x, y, z) { // ... } var args = [0, 1, 2]; f.apply(null, args); // ES6的写法 function f(x, y, z) { // ... } 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);
上面代码表示, 因为JavaScript不提供求数组最大元素的函数, 因此只能套用Math.max函数, 将数组转为一个参数序列, 而后求最大值。 有了扩展运算
符之后, 就能够直接用Math.max对象
3.合并数组ip
// ES5的写法 [1, 2].concat(more) // ES6 [1, 2, ...more] var arr1 = ['a', 'b']; var arr2 = ['c']; var arr3 = ['d', 'e']; // ES5的合并数组 arr1.concat(arr2, arr3); // [ 'a', 'b', 'c', 'd', 'e' ] // ES6的合并数组 [...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ]