是否可以将函数的所有参数作为该函数内的单个对象获取?

在PHP中,有func_num_argsfunc_get_args,JavaScript是否有类似的东西?


答案 1

对于现代Javascript或Typescript:

class Foo {
    reallyCoolMethodISwear(...args) { return args.length; }
}

function reallyCoolFunction(i, ...args) { return args[i]; }

const allHailTheLambda = (...args) => {
    return args.constructor == Array;
};

const x = new Foo().reallyCoolMethodISwear(0, 1, 2, 3, 4);
const y = reallyCoolFunction(3, 0, 1, 2, 3, 4, 5, 6);
const z = allHailTheLambda(43110, "world");

console.log(x, y, z); // 5 3 true

对于古代Javascript:

使用参数。您可以像数组一样访问它。用于参数数。arguments.length


答案 2

参数类似数组的对象(而不是实际的数组)。示例函数...

function testArguments () // <-- notice no arguments specified
{
    console.log(arguments); // outputs the arguments to the console
    var htmlOutput = "";
    for (var i=0; i < arguments.length; i++) {
        htmlOutput += '<li>' + arguments[i] + '</li>';
    }
    document.write('<ul>' + htmlOutput + '</ul>');
}

试试看...

testArguments("This", "is", "a", "test");  // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9);          // outputs [1,2,3,4,5,6,7,8,9]

完整详情:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments