ES6+功能 剩余参数

剩余参数

  • 剩余参数语法允许我们将一个不定数量的参数表示为一个数组
  • 不定参数定义方式,这种方式很方便的去声明不知道参数情况下的一个函数
  const sum = (...args) => {
              let total = 0;
              args.forEach((item) => {
                  total += item;
              })
              return total;
          }
          console.log(sum(10, 20));
          console.log(sum(10, 20, 30));
  • 剩余参数和解构配合使用
  let students = ['wangwu', 'zhangsan', 'lisi'];
          let [s1, ...s2] = students;
          console.log(s1); // 'wangwu' 
          console.log(s2); // ['zhangsan', 'lisi']
  • 其中 … 称之为展开运算符
  • 扩展运算符可以将数组或者对象转为用逗号分隔的参数序列
  let ary = [1, 2, 3];
   // ...ary // 1, 2, 3
   console.log(...ary); // 1 2 3,相当于下面的代码
   console.log(1, 2, 3);
  • 数组合并案例
  console.log('------------数组合并案例--------------------');
          var arr1 = [1, 2, 3]
          var arr2 = [4, 5, 6]
          var arr3 = [...arr1, ...arr2]
          console.log(arr3);
  • 求最大值案例
 console.log('-----------求最大值----------------');
  var arr4 = [1, 2, 3, 4, 5, 67]
  console.log(Math.max.apply(Math, arr4));
  console.log(Math.max(...arr4));
  • 将伪数组转换为真正的数组
  console.log('----------------3.将伪数组转化为真正的数组----------------');
          var liArr = document.querySelectorAll('li');
          console.log(liArr);
          console.log([...liArr]);
  • 利用Array.from 方法将伪数组转换为真正的数组
const arraylike = {
              '0': 'gy',
              '1': 'ckx',
              '2': 'gyq',
              '3': 'ghy',
              length: 4
          }
          console.log('----------------------伪数组-----------------------------');
          console.log(arraylike);
          console.log('----------利用Array.from 方法将伪数组转换为真正的数组---------');
          var newArray = Array.from(arraylike);
          console.log(newArray);
  • 利用Array.from 方法将伪数组转换为真正的数组的第二个参数
  const arraylike2 = {
              '0': 1,
              '1': 2,
              '2': 3,
              '3': 4,
              length: 4
          }
          var newArray2 = Array.from(arraylike2, item => item * 2);
          console.log(newArray2);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂平头哥前端乐园

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值