美文网首页
rest参数

rest参数

作者: 在下高姓 | 来源:发表于2020-05-15 16:02 被阅读0次

    为了获取除了已定义参数a、b之外的参数,我们不得不用arguments,并且循环要从索引2开始以便排除前两个参数,这种写法很别扭,只是为了获得额外的rest参数

    ES6标准引入了rest参数,获取形参以外的所有参数
    function foo(a, b, ...rest) {
        console.log('a = ' + a);
        console.log('b = ' + b);
        console.log(rest);
    }
    
    foo(1, 2, 3, 4, 5);
    // 结果:
    // a = 1
    // b = 2
    // Array [ 3, 4, 5 ]
    
    foo(1);
    // 结果:
    // a = 1
    // b = undefined
    // Array []
    
    rest参数只能写在最后,前面用...标识
    

    相关文章

      网友评论

          本文标题:rest参数

          本文链接:https://www.haomeiwen.com/subject/gowcohtx.html