在JS的function函数体(仅限function函数,不包括箭头函数)内,可以通过argument类数组对象来访问该函数的全部参数:
function func(a,b,c){
console.log(a,b,c)
console.log(arguments[0],arguments[1],arguments[2])
console.log(arguments.length)
}
func('a','b','c')
// a b c
// a b c
// 3
可以看到arguments由传递到函数中的参数组成,值和数量完全一致,需要注意以下几种情况:
function func(a,b,c){
console.log(arguments[0],arguments[1],arguments[2],arguments[3])
console.log(arguments.length)
}
func('a','b')
// a b undefined undefined
// 2
func('a','b','c')
// a b c undefined
// 3
func('a','b','c','d')
// a b c d
// 4
console.log(func.length)
// 3
可以看到arguments是有函数调用时传递的参数决定的,即使函数中没有定义的参数通过arguments也能取到,而通过获取function的length属性取得的值始终等于函数定义的参数个数,与调用无关。下面的代码将尝试修改arguments并观察参数变化:
function func(a,b,c){
arguments[0]++
arguments[1]++
arguments[2]++
console.log(a,b,c)
}
func(1,2,3)
// 2 3 4
可以看到当修改arguments时,使用形参取得的参数值也发生了改变,这说明arguments中的元素与函数调用时形参所对应的实参指向的是同一个内存地址,但是需要注意以下情况:
function func(a,b,c){
arguments[0] = 1
arguments[1] = 2
arguments[2] = 3
console.log(a,b,c)
}
func()
// undefined undefined undefined
可以看到,如果调用函数时没有传递参数,通过修改arguments是无法将参数值同步给形参取得的。
由于arguments是一个类数组对象,所以并不具备数组的方法,使用时需要通过call或apply调用数组原型中的方法:
function func(a,b,c){
/*
let A = arguments.slice(0,1) // 报错
let B = arguments.slice(1,2) // 报错
let C = arguments.pop() // 报错
*/
let A = Array.prototype.slice.call(arguments,0,1) // a
let B = Array.prototype.slice.apply(arguments,[0,1]) // b
let C = Array.prototype.pop.call(arguments) // c
console.log(A,B,C)
console.log(arguments.length)
}
func(1,2,3)
// [1] [2] 3
// 2
同时arguments还具备一个callee属性,指向函数自身,可以用来实现匿名函数递归:
function func(a,b,c){
console.log(a,b,c)
Array.prototype.pop.call(arguments)
if(arguments.length){
arguments.callee.apply(null,arguments)
}
}
func(1,2,3)
// 1 2 3
// 1 2 undefined
// 1 undefined undefined