PHP中有func_num_args和func_get_args, JavaScript中也有类似的东西吗?


当前回答

正如许多人指出的那样,参数包含传递给函数的所有参数。

如果您想调用另一个具有相同参数的函数,请使用apply

例子:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

其他回答

对于现代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:

使用参数。你可以像访问数组一样访问它。使用参数。参数个数的长度。

正如许多人指出的那样,参数包含传递给函数的所有参数。

如果您想调用另一个具有相同参数的函数,请使用apply

例子:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

ES6允许使用“…”符号指定函数参数的构造,例如

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

希望这能有所帮助:

function x(...args) {
    console.log( {...[...args] } ); 
}

x({a:1,b:2}, 'test');

输出:

{ '0': { a: 1, b: 2 }, '1': 'test' }

在ES6中,你可以这样做:

函数foo (args…) { Let [a,b,…c] = args; console.log (a, b, c); } Foo (1, null,"x",true, undefined);