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);

其他回答

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

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

例子:

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

debug("message", "another argument")

与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

希望这是有用的代码:

function lazyLoadIcons(){
    for(let i = 0; i < arguments.length; i++) {
        var elements = document.querySelectorAll(arguments[i]);
        elements.forEach(function(item){
            item.classList.add('loaded');
        });
    }
}

lazyLoadIcons('.simple-2col', '.ftr-blue-ad', '.btm-numb');  

~拉胡尔·达克什

在ES6中,你可以这样做:

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

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

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