函数参数

  1. 所谓类数组对象,就是指可以通过索引属性访问元素并且拥有 length 属性的对象;

    var arrLike = {
      0: 'name',
      1: 'age',
      2: 'job',
      length: 3
    }
    
  2. ES5 中,函数经常会传入不定参数,在传入不定参数时,ES5 的给出的解决方案是通过 arguments 对象来获取函数调用时传递的参数。 arguments 对象不是一个数组,它是一个类数组对象;尽管 arguments 是一个类数组且可遍历的变量,但它终究不是数组,它不支持数组方法,因此不能调用 arguments.forEeach (…) 等数组的方法

    function fn() {
        console.log(arguments);
    }
    fn('hello', 7, 'ES6')
    
  3. ES6 给出了完美解决方案 —— 剩余参数

    function fn(name, ...args) {
      console.log(name);  // 基础参数
      console.log(args);  // 剩下的参数组成的数组
    }
    
    fn('ES6');
    //	'ES6'
    //	[]
    
    fn('hello', 7, 'ES6');
    //  "hello"
    //	[7, "ES6"]
    

解构剩余参数

  1. 数组的解构赋值

    let array = [1, 2, 3, 4, 5];
    let [a, b, ...others] = array;
    console.log(a);					 // 1
    console.log(b);					 // 2
    console.log(others);		 // [3, 4, 5]
    
  2. 对象的解构赋值

    let {a, b, ...others } = {a: 1,  b: 2,  c: 3,  d: 4,  e: 5}
    console.log(a);					// 1
    console.log(b);					// 2
    console.log(others);		// {c: 3,  d: 4,  e: 5}
    

小结

  1. 剩余参数是为了能替代函数内部的 arguments 而引入的;

  2. 和展开语法相反,剩余参数是将多个单个元素聚集起来形成一个单独的个体的过程;

打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于产品、设计、开发的问题和看法,还有技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程

了解更多

目录

  1. 1. 函数参数
  2. 2. 解构剩余参数
  3. 3. 小结