Skip to content

3.JS 中的 arguments

什么是 arguments(arguments 是数组还是对象)

arguments 存储着函数的实参。,拥有着 length 属性,是个类数组(对象)。

运用

检查函数实参和形参个数

js
function fn(a, b, c) {
  if (fn.length != arguments.length) throw new Error("auguments length Error");
}

实现匿名函数递归

arguments 中的 callee 属性指向当前函数,可以利用这个特性实现匿名函数递归

js
  function fn(oldTime) (
    let time = 10
    return function(){
      if(Date.now() - oldTime > time) {
        return arguments.callee(oldTime)
      }
    }
  )

模拟函数重载

js
function doAdd() {
  if (arguments.length == 1) {
    console.log(arguments[0] + 5);
  } else if (arguments.length == 2) {
    console.log(arguments[0] + arguments[1]);
  }
}
doAdd(10); // 15
doAdd(10, 20); // 30

KESHAOYE-知识星球 V20250206145514