


Web培训
400-996-5531
arguments是一个对应于传递给函数的参数的类数组对象。
一、arguments的使用
当我们不确定有多少个参数传递的时候,可以用arguments来获取。在JavaScript中,arguments实际上它是当前函数的一个内置对象。所有函数都内置了一个arguments对象,arguments对象中存储了传递的所有实参。
arguments展示形式是一个伪数组,因此可以进行遍历。伪数组具有以下特点:
具有length属性
按索引方式储存数据
不具有数组的push,pop等方法
使用场景
利用函数求任意个数的最大值
functionmaxValue(){
varmax=arguments[0];
for(vari=0;i<arguments.length;i++)
{
if(max<arguments[i]){
max=arguments[i];
}
}
returnmax;
}
console.log(maxValue(2,4,5,9));
console.log(maxValue(12,4,9));
在实际开发,建议不要再使用arguments了,请使用ES6的解构语法,比下:
functionmaxValue(...data){
letmax=data[0]
for(leti=0;
i<data.length;i++){
if(max<data[i]){
max=data[i];
}
}
returnmax;
}
console.log(maxValue(2,4,5,9));
console.log(maxValue(12,4,9));
二、arguments.callee的使用
callee是arguments对象的属性。在函数体内,它指向当前正在执行的函数。
ECMAScript5禁止在严格模式中使用arguments.callee()。当一个函数必须调用自身的时候,假如它是函数表达式则给它命名,或者使用函数声明,避免使用arguments.callee()
使用场景
使用arguments.callee最常见的情景是当我们要创造一个递归函数的时候:
functionfactorial(num){
if(num<=1){
return1;
}
else{
returnnum*arguments.callee(num-1);
}
}
console.log(factorial(4));//24
但是如果代码是在严格模式下开发,使用"usestrict";则会出现报错信息:
UncaughtTypeError:'caller','callee',and'arguments'propertiesmaynotbeaccessedonstrictmodefunctionsortheargumentsobjectsforcallstothem
在严格模式下不能通过脚本访问arguments.callee,访问这个属性会报错,那么可以使用命名函数表达式来达到相同的结果:
"usestrict";varfactorial=(functionf(num){
if(num<=1){
return1;
}
else{
returnnum*f(num-1);
}
}
)
console.log(factorial(4));//24
填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!
Copyright © 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有