arguments

2019-07-29  本文已影响0人  你喜欢吃青椒吗_c744

定义

arguments[0]
arguments[1]
arguments[2]
//参数也可以被设置:
arguments[1] = 'new value';

请注意

如何把arguments转化为数组

//es5
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
//es5的新写法。
//因为使用slice会阻止某些JavaScript引擎中的优化
//可以尝试通过遍历arguments对象来构造一个新的数组
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
//es6的两种写法
const args = Array.from(arguments);//第一种
const args = [...arguments];//第二种。扩展运算符

对arguments使用typeof

typeof参数返回 'object'。

console.log(typeof arguments);    // 'undefined'
// arguments 对象只能在函数内使用
function test(a){
    console.log(a,Object.prototype.toString.call(arguments));
    console.log(arguments[0],arguments[1]);
    console.log(typeof arguments[0]);
}
test(1);
/*
1 "[object Arguments]"
1 undefined
number
*/
//可以使用索引确定单个参数的类型。
console.log(typeof arguments[0]);

属性

function argTest(a,b,c){
    var e = arguments.callee.toString();
    console.log(e);
}
argTest(); //打印出函数本身
function argTest(a,b,c){
    var t = arguments.length; //实际传参个数
    var e = argTest.length;   //期望传参个数
    console.log(t);
    console.log(e);
}
argTest(11,12);       //t=2,e=3
argTest(11,12,13);    //t=3,e=3
argTest(11,12,13,14); //t=4,e=3
function argTest(a,b,c){
    var arg = [];
    for(var i=0;i<arguments.length;i++){
        arg.push(arguments[i]);
    }
    console.log(arg);
}
argTest(11,12);       //[11, 12]
argTest(11,12,13);    //[11, 12, 13]
argTest(11,12,13,14); //[11, 12, 13, 14]

实现递归调用

可以实现匿名函数的递归调用。

//实现一个阶乘函数
function factorial(n){
    if(n == 1){
        return 1;
    }else{
        n * arguments.callee(n-1);
    }
}
factorial(1); //1
factorial(5); //120

参考文章

Arguments 对象

Arguments对象作用深度研究

JS中的arguments参数

上一篇 下一篇

猜你喜欢

热点阅读