一、arguments对象是什么
JavaScript中的函数作用域都有一个特殊的对象,被称为arguments对象。它类似于一个数组,包含了调用函数时传入的所有参数。arguments对象是函数内部可访问的局部变量,它的长度没有限制。 以下代码是一个经典的计算不定参数的函数,使用了arguments:
function multiply(){
var result = 1;
for(var i = 0; i < arguments.length; i++){
result *= arguments[i];
}
return result;
}
二、arguments对象的属性
arguments对象具有以下属性:
1. length
length是arguments对象的一个属性,表示传入函数的参数个数。
function someFunction(){
console.log(arguments.length); // 打印传入参数个数
}
someFunction(1, 2, 3); //输出结果:3
2. callee
callee是arguments对象的一个属性,它指向当前正在执行的函数。
function factorial(n){
if(n == 1){
return 1;
}else{
return n * arguments.callee(n - 1); //调用自身
}
}
三、arguments对象的方法
arguments对象具有以下方法:
1. call() 和 apply()
这两个方法都允许显式地设置函数执行时的上下文(即this
关键字的值)和参数列表。区别在于参数列表的方式不同。
function log(){
console.log.apply(console, arguments); //使用apply动态传入参数
}
log('hello', 'world'); //输出结果:hello world
2. slice()
slice方法可以将arguments对象转化为一个真正的数组,它的作用是返回从起始索引号指定的位置开始到结束索引号指定的位置的所有元素。
function hello(){
var helloArray = Array.prototype.slice.call(arguments); //将arguments对象转为数组
console.log(helloArray); //输出结果:['hello', 'world']
}
hello('hello', 'world');
四、使用arguments的注意事项
虽然arguments是很方便实用的,但也需要注意一些细节:
1. 严格模式下无法使用arguments.callee
在严格模式下,不能访问arguments.callee方法。
'use strict';
function factorial(n){
if(n == 1){
return 1;
}else{
return n * factorial(n - 1); //直接调用函数本身
}
}
2. 改变arguments的值也会改变对应的参数
arguments和对应的参数是关联的,修改任意一个都将影响另一个。
function foo(x){
arguments[0] = 99; //修改arguments的值
console.log(x); //输出结果:99
}
foo(10); //调用函数
五、总结
arguments是一个非常实用的JavaScript对象,可以让我们更方便地处理不定数量的参数。