0

arguments的使用

 2 years ago
source link: https://www.fly63.com/article/detial/11307
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
更新日期: 2022-03-30阅读量: 3标签: 对象分享

扫一扫分享

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,访问这个属性会报错,那么可以使用命名函数表达式来达到相同的结果:

"use strict";
var factorial = (function f(num){
if(num<=1){
return 1;
}else {
return num * f(num-1);
}
})

console.log(factorial(4)); //24

链接: https://www.fly63.com/article/detial/11307


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK