将 "arguments" 转变为 Array 的多种姿势

来源:互联网 发布:csoldjb9.0最终优化 编辑:程序博客网 时间:2024/06/11 17:39

在javascript中,arguments 对于 function 来说是一个非常重要的内定义数组,它拥有函数调用时所有传入的参数,这就是说我们可以在函数内遍历它来获取传入的所有参数,但是如果直接这样:

    function Fun(){        arguments.forEach(function(value){            console.log(value);        });    };    Fun(1,2,3,4,5,6,7,8,9,10);

运行时会报错

    TypeError: arguments.forEach is not a function

使用typeof来查看一下arguments的类型:

    console.log(typeof arguments);

运行得到如下结果

    object

数组是特殊的对象,forEach()是专为数组遍历的函数,所以我们要把arguments转变为Array类型。


注意:以下均是在函数内部的语句

  • 方法一
    var args = Array.prototype.slice.call(arguments);    args.forEach(function(value){});
  • 方法二
    var args = [].slice.call(arguments);    args.forEach(function(value){});
  • 方法三
    var args = Array.from(arguments);    args.forEach(function(value){});
  • 方法四
    var args = Array.apply(null,arguments);    args.forEach(function(value){});

其实本意是要遍历arguments的,所以还有两种种不用转化为数组直接遍历的方案

  • 方法一
    for(var i=0; i<arguments.length; i++){}
  • 方法二
    for(key in arguments){        console.log(key);    };

当然,你也可以选择这么写函数,只不过这是遵循最新的ES6标准

//ES6新方法    function Fun(...args){        args.forEach(function(value){});    };

0 0
原创粉丝点击