来源 |
arguments 是一个对应于传递给函数的参数的类数组对象。
一、arguments的使用
当我们不确定有多少个参数传递的时候,可以用 arguments 来获取。在 JavaScript 中,arguments 实际上它是当前函数的一个内置对象。所有函数都内置了一个 arguments 对象,arguments 对象中存储了传递的所有实参。
arguments展示形式是一个伪数组,因此可以进行遍历。伪数组具有以下特点:
具有 length 属性
按索引方式储存数据
不具有数组的 push , pop 等方法使用场景
利用函数求任意个数的最大值
function maxValue() {
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i];
}
}
return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));
在实际开发,建议不要再使用arguments了,请使用ES6的解构语法,比下:
function maxValue(...data) {
let max=data[0]
for (let i = 0; i < data.length; i++) {
if (max < data[i]) {
max = data[i];
}
}
return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));
二、arguments.callee的使用
callee是arguments对象的属性。在函数体内,它指向当前正在执行的函数。
ECMAScript 5 禁止在严格模式中使用 arguments.callee()。当一个函数必须调用自身的时候,假如它是函数表达式则给它命名,或者使用函数声明,避免使用 arguments.callee()
使用场景
使用arguments.callee最常见的情景是当我们要创造一个递归函数的时候:
function factorial(num){
if(num<=1){
return 1;
}else {
return num * arguments.callee(num-1);
}
}
console.log(factorial(4)); //24
但是如果代码是在严格模式下开发,使用"use strict";则会出现报错信息:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
在严格模式下不能通过脚本访问arguments.callee,访问这个属性会报错,那么可以使用命名函数表达式来达到相同的结果:
;
var factorial = (function f(num){
if(num<=1){
return 1;
}else {
return num * f(num-1);
}
})
console.log(factorial(4)); //24
本文完~
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。