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
其他回答
在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
希望这能有所帮助:
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]);
}
是的,如果你不知道在函数声明时可能有多少参数,那么你可以声明不带形参的函数,并且可以通过函数调用时传递的参数数组访问所有变量。
推荐文章
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 四舍五入到一个数字的最接近倍数
- 相当于字符串。jQuery格式
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?