zoukankan      html  css  js  c++  java
  • Arguments对象

    Part 1

    Arguments对象是一个类数组对象,用来表示传递给JS方法的参数:

    function testArgs(a,b,c){
                console.log(arguments[0]);
                //expected output:1
                console.log(arguments[1]);
                //expected output:2
                console.log(arguments[2]);
                //expected output:3
    }    
    testArgs(1,2,3);

    这里说的Arguments对象是类数组对象指的是它具有length属性,也就是说对象内的元素索引都是从0开始的。但是它不具备一些Array含有的内置方法,比如forEach()或Map();

    Arguments是所有的(非箭头)函数中都可使用的局部变量,我们可以使用Array.from()方法或者扩展运算符把它转换成为一个数组对象:

    const args = Array.from(arguments);
    const args = [...arguments];

    以上是ES6写法,还有另外一种性能较好的写法:

    1 var args = (arguments.length == 1?[arguments[0]]:Array.apply(arguments));

    判断一下arguments的长度,如果只有一个元素,那么直接强制类型转换为数组,否则使用array.apply()方法将类数组对象转换为数组对象。

    但在Chrome 14 以及 Internet Explorer 9 中如果向apply方法中传入类数组对象会抛出异常。

    Part 2

    剩余参数和Arguments对象的区别:

    • 剩余参数只是用来表示那些没有形参对应的实参们,但是arguments表示的是传给方法的所有实参。
    • arguments对象只是一个类数组对象,但剩余参数是真正的数组实例,也就是说剩余参数具有array对象的所有内置方法(push,pop...);
    • arguments对象还有除了和数组对象相同的属性之外的其他属性,比如callee属性。
  • 相关阅读:
    JavaScript实现继承的几种方式总结一
    MyISAM key 压缩
    Visual Studio2010英文版安装中文帮助文档
    回忆我是怎样走上程序之路的(上)起因
    hdu2054 A==B
    顺序表的增删排序
    hdu2145 zz's Mysterious Present
    hdu 2141 Can you find it?
    hdu1162 Eddy's picture
    hdu1142 A Walk Through the Forest
  • 原文地址:https://www.cnblogs.com/zhangxin123/p/13647172.html
Copyright © 2011-2022 走看看