定义
-
arguments
是一个对应于传递给函数的参数的伪数组对象。 -
arguments
对象是所有(非箭头)函数中都可用的局部变量。 - 你可以使用
arguments
对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。例如,如果一个函数传递了三个参数,你可以以如下方式引用他们:
arguments[0]
arguments[1]
arguments[2]
//参数也可以被设置:
arguments[1] = 'new value';
请注意
-
arguments
对象不是一个Array
数组。 - 它类似于
Array
,但除了length
属性和索引元素之外没有任何Array
属性。可以arguments[i]
来访问对象中的元素,但它不能用数组的一些方法,例如push,pop,slice
等。 - 如果调用的参数多于正式声明接受的参数,则可以使用arguments对象。
- 这种技术对于可以传递可变数量的参数的函数很有用。使用
arguments.length
来确定传递给函数参数的个数,然后使用arguments
对象来处理每个参数。要确定函数签名
中(输入)参数的数量,请使用Function.length
属性。 - 函数调用的时候,浏览器每次都会传递进两个隐式参数:
- 函数的上下文对象this
- 封装实参的对象arguments
如何把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]);
属性
-
arguments.callee
指向当前执行的函数。当函数正在执行时才可调用,可以实现方法的递归调用。
function argTest(a,b,c){
var e = arguments.callee.toString();
console.log(e);
}
argTest(); //打印出函数本身
-
arguments.caller
指向调用当前函数的函数 -
arguments.length
指向传递给当前函数的参数数量。
Arguments的length属性,表示function函数实际所传参数的个数。
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
-
arguments[@@iterator]
返回一个新的Array迭代器对象,该对象包含参数中每个索引的值。 - arguments的参数访问
Arguments对象的参数访问可以用arguments[i]来访问函数所传的参数。
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
网友评论