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


当前回答

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 += '<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

其他回答

是的,如果你不知道在函数声明时可能有多少参数,那么你可以声明不带形参的函数,并且可以通过函数调用时传递的参数数组访问所有变量。

arguments对象是存储函数参数的地方。

arguments对象的行为和看起来像一个数组,它基本上是,它只是没有数组的方法,例如:

Array。forEach (callback黑,thisArg铝);

阵列。(回调,thisArg文件夹)

Array。filter (callback黑,thisArg铝);

数组中。片(开始[结束])

数组中。indexOf (searchElement [, fromIndex])

我认为将arguments对象转换为真实数组的最好方法如下:

argumentsArray = [].slice.apply(arguments);

这将使它成为一个数组;

可重用:

function ArgumentsToArray(args) {
    return [].slice.apply(args);
}

(function() {
   args = ArgumentsToArray(arguments);

   args.forEach(function(value) {
      console.log('value ===', value);
   });

})('name', 1, {}, 'two', 3)

结果:

> value === name > value === 1 >值===对象{} > value === 2 > value === 3

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

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

例子:

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

debug("message", "another argument")

在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