• JavaScript系列之剩余参数



    一、概述

    剩余参数语法允许我们将一个不定数量的参数表示为一个数组。

    二、语法

    function (a, b, ...theArgs) {
    	// ...
    }
    
    • 1
    • 2
    • 3

    三、描述

    如果函数的最后一个命名参数以...为前缀,则它将成为一个由剩余参数组成的真数组,其中从 0(包括)到theArgs.length(排除)的元素由传递给函数的实际参数提供。

    1、剩余参数和 arguments对象的区别

    • 剩余参数只包含那些没有对应形参的实参,而 arguments 对象包含了传给函数的所有实参。
    • arguments对象不是一个真正的数组,而剩余参数是真正的 Array 实例,也就是说你能够在它上面直接使用所有的数组方法,比如 sort,map,forEach或pop。
    • arguments对象还有一些附加的属性 (如callee属性)。

    2、从 arguments 到数组

    引入了剩余参数来减少由参数引起的样板代码。

    // Before rest parameters, "arguments" could be converted to a normal array using:
    
    function f(a, b) {
    	var normalArray = Array.prototype.slice.call(arguments);
    	// -- or --
    	var normalArray = [].slice.call(arguments);
    	// -- or --
    	var normalArray = Array.from(arguments);
    
    	var first = normalArray.shift(); // OK, gives the first argument
    	var first = arguments.shift(); // ERROR (arguments is not a normal array)
    }
    
    // Now we can easily gain access to a normal array using a rest parameter
    
    function f(...args) {
    	var normalArray = args;
    	var first = normalArray.shift(); // OK, gives the first argument
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3、解构剩余参数

    剩余参数可以被解构,这意味着他们的数据可以被解包到不同的变量中。请参阅解构赋值

    function f(...[a, b, c]) {
    	return a + b + c;
    }
    
    f(1); // NaN (b and c are undefined)
    f(1, 2, 3); // 6
    f(1, 2, 3, 4); // 6 (the fourth parameter is not destructured)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    四、示例

    因为theArgs是个数组,所以你可以使用length属性得到剩余参数的个数:

    function fun1(...theArgs) {
    	alert(theArgs.length);
    }
    
    fun1(); // 弹出 "0", 因为 theArgs 没有元素
    fun1(5); // 弹出 "1", 因为 theArgs 只有一个元素
    fun1(5, 6, 7); // 弹出 "3", 因为 theArgs 有三个元素
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    写在最后

    如果你感觉文章不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
    如果你觉得该文章有一点点用处,可以给作者点个赞;\\*^o^*//
    如果你想要和作者一起进步,可以微信扫描二维码,关注前端老L~~~///(^v^)\\\~~~
    谢谢各位读者们啦(^_^)∠※!!!

  • 相关阅读:
    好代码 ,坏代码:你的代码和其他工程师的代码
    NC17383 A Simple Problem with Integers
    一文带你认知定时消息发布RocketMQ
    python高级内置函数介绍及应用举例
    805.数组的均值分割(回溯+折半搜索+数学)
    【Docker】docker安装nacos
    【Linux】yum/git/gdb
    Spring的AOP介绍和使用
    中国大模型开源创新与合作的新篇章 | 2023 CCF中国开源大会
    SpringMVC概述及入门案例
  • 原文地址:https://blog.csdn.net/weixin_62277266/article/details/126917183