rest参数与扩展运算符

Posted on 2019-03-23 00:35  zhangzhengsmiling  阅读(424)  评论(0)    收藏  举报

rest参数与扩展运算符

  1. rest参数

    当遇上这样一种需求:对于输入的参数,求和返回,但传入的参数个数并不确定。 

    // 在es5中,通常是使用函数自身的arguments对象实现的
     function sum () {
         let sum = 0;
         for(let i = 0; i < arguments.length; i++) {
             sum += arguments[i];
         }
         return sum;
     }
     ​
     // 使用Array.from将其转化为数组,就可以使用数组的方法
     function sum () {
         // arguments对象是一个伪数组,必须转化为数组才能使用reduce方法
         return Array.from(arguments).reduce((temp, value) => temp + value, 0);
     }
     // 使用Array.prototype.call()方法返回一个数组对象 --> 将伪数组转换为数组
     function sum () {
         return Array.prototype.call(arguments).reduce((temp, value) => temp +value, 0);
     }
     ​
     // ES6中还可以通过rest参数接收函数参数,并转换成一个数组
     function sum (...plus) {
         return plus.reduce((temp, value) => temp + value, 0);
     }

    注意:rest参数只能作为函数的最后一个参数,否则会报错

    function func (a, ...rest, b) {
         // do something
     }
     // Rest Parameter must be last formal paramter
  2. 扩展运算符

    扩展运算符与rest参数恰好是一个逆过程,rest参数是将多个参数转换成一个数组,而运算符扩展则是将一个数组扩展成多个参数的形式。

     // 现有一个数组
     let arr = [1, 2, 3, 4, 5];
     // 有一个求和函数
     function sum (...rest) {
         return rest.reduce((temp, value) => temp + value, 0);
     }
     // 现在需要通过sum函数对数组进行求和操作,但是函数需要的参数不是数组
     // 在es5中是不容易实现的
     // 但是使用扩展运算符,恰好可以解决问题
     sum(...arr);
     let arr1 = [1, 2, 3, 4, 5];
     let arr2 = [6, 7, 8];
     // 求arr1和arr2所有元素的和
     sum(...arr1, ...arr2);

    扩展运算符还可以用于数组的复制

    let arr1 = [1, 2, 3, 4];
     // ...arr1 扩展运算符就相当于 1, 2, 3, 4 --> 即数组的展开
     let copy = [...arr1];

    对于任何实现了遍历器接口(Iterator)的对象都可以使用扩展运算符

     let lis = document.querySelectorAll('li');
     console.log(...lis); // <li>a</li> <li>b</li> <li>c</li>
     // querySelectorAll()函数返回的是一个NodeList对象(注意:与document.get...系列返回的HTML集合是不一样的)
     let lisList = [...lis];
     // 内部的...后的参数是一个NodeList对象,NodeList对象实现了遍历器接口,因此能够用扩展运算符进行扩展,而后形成一个新数组,使用该方法可以将伪数组转化为数组