在函数内部作为单个对象获取所有参数是否可行?

13 浏览
0 Comments

在函数内部作为单个对象获取所有参数是否可行?

在PHP中有func_num_argsfunc_get_args,那么JavaScript中有类似的东西吗?

admin 更改状态以发布 2023年5月22日
0
0 Comments

arguments 是一个类似数组对象(不是实际的数组)。例如函数...

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 += '
  • ' + arguments[i] + '
  • '; } document.write('
      ' + htmlOutput + '
    '); }

    试试它...

    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

    0
    0 Comments

    对于现代的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。你可以像访问数组一样访问它。使用arguments.length获取参数数量。

    0