温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ES6中剩余参数的案例分析

发布时间:2020-12-08 10:47:19 来源:亿速云 阅读:156 作者:小新 栏目:web开发

这篇文章主要介绍了ES6中剩余参数的案例分析,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

概述

剩余参数将没有对应形参的参数聚合成一个数组

语法

function(a, b, ...theArgs) {
}

只聚合未对应形参参数

剩余参数只会将没有对应形参的参数聚合成一个数组, 而arguments则是包含了所有的参数。

function add(a, b, ...theArgs) {
    return {rest: theArgs, arguments}
}
add() 
// {rest: [undefined, undefined, []], arguments: Arguments(0)}
add(1) 
// {rest: [1, undefined, []], arguments: Arguments(1)}
add(1, 2) 
// {rest: [1, 2, []], arguments: Arguments(2)}
add(1, 2, 3, 4, 5) 
// {rest: [1, 2, [3, 4, 5]], arguments: Arguments(5)}

剩余参数是数组

剩余参数始终是一个数组,而不像arguments是一个伪数组

function add(...theArgs) {
    console.log(Array.isArray(theArgs))
    theArgs.forEach((a)=>console.log(a))
    console.log(Array.isArray(arguments))
    Array.prototype.slice.call(arguments, add.length).forEach((a)=>console.log(a)) // 转化成数组
}
add(1,2,3) // true 1 2 3 false 1, 2, 3, 4

解构剩余参数

function add(...[a, b, c]){
    return a + b +c
}
add(1, 2, 3) // 6
add(1, 2, 3) // 6

使用babel翻译

function add(...num){
  return num.reduce((n1,n2)=>n1+n2)
}

翻译后

function add() {
  for (var _len = arguments.length, num = Array(_len), _key = 0; _key < _len; _key++) {
    num[_key] = arguments[_key];
  }

  return num.reduce(function (n1, n2) {
    return n1 + n2;
  });
}

感谢你能够认真阅读完这篇文章,希望小编分享ES6中剩余参数的案例分析内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI