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


当前回答

在ES6中,你可以这样做:

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

其他回答

与Gunnar的回答相似,但有更完整的例子: 你甚至可以透明地返回整个东西:

function dumpArguments(...args) {
  for (var i = 0; i < args.length; i++)
    console.log(args[i]);
  return args;
}

dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });

输出:

foo
bar
true
42
["yes","no"]
{"banana":true}

https://codepen.io/fnocke/pen/mmoxOr?editors=0010

如果您愿意,还可以将其转换为数组。如果Array泛型可用:

var args = Array.slice(arguments)

否则:

var args = Array.prototype.slice.call(arguments);

来自Mozilla MDN:

您不应该对参数进行切片,因为这会阻止在 JavaScript引擎(例如V8)。

在ES6中,你可以这样做:

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

希望这能有所帮助:

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

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

输出:

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

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

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