灏天阁

函数参数

· Yin灏

检测一个函数的形参和实参是否一致

function checkArg(a) {
    // arguments.callee.length 获取形参的个数
    if (a.length != a.callee.length) {
        throw new Error('实参和形参不一致');
    }
}
function f(a, b) {
    checkArg(arguments);
    return ((a * 1 ? a : 0) + (b * 1 ? b : 0)) / 2;
}
console.log(f(6)); // Uncaught Error: 实参和形参不一致

使用 arguments 对象

arguments 对象表示函数的实参集合。arguments 对象是一个伪类数组,不能继承 Array 的原型方法。可以使用数组下标的形式访问每个实参,如 arguments[0]

  • 使用 for 循环遍历 arguments 对象,然后把循环变量的值传入 arguments,以便改变实参值
function f() {
    for(var i = 0; i < arguments.length; i++) {
        arguments[i] = i;
        console.log(arguments[i]); // 0 1 2 改变了实参的值
    }
}
f(3, 3, 6); 

使用 callee

calleearguments 对象的属性,它引用当前 arguments 对象所在的函数。使用该属性可以在函数体内调用函数自身。在匿名函数中,callee 比较有用,例如,利用它可以设计递归调用。

/*
  使用 arguments.callee 获取匿名函数,然后通过函数的 length 属性获取函数形参个数,最后比较实参和形参的个数。
*/
function f(x,y,z) {
    var a = arguments.length; // 获取函数实参的个数
    var b = arguments.callee.length; // 获取函数形参的个数
    if(a != b) {
        throw new Error('传递参数不匹配');
    } else {
        return x + y + z;
    }
}
console.log(f(3, 4, 5)); // 12
// arguments.callee 等价于函数名,上面等于 f

使用动态调用的方法,让 arguments 对象调用数组方法 slice(),可以把函数的参数对象转换为数组。

function f() {
    console.log(arguments); // Arguments { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, … }
    return [].slice.apply(arguments); // 等价于 (new Array()).slice.apply(arguments)  // 等价于 Array.from(arguments)
}
console.log(f(1, 2, 3, 4, 5, 6)); // [ 1, 2, 3, 4, 5, 6 ]

- Book Lists -