PHP中有func_num_args和func_get_args, JavaScript中也有类似的东西吗?
当前回答
对于现代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:
使用参数。你可以像访问数组一样访问它。使用参数。参数个数的长度。
其他回答
在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
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
希望这能有所帮助:
function x(...args) {
console.log( {...[...args] } );
}
x({a:1,b:2}, 'test');
输出:
{ '0': { a: 1, b: 2 }, '1': 'test' }
是的,如果你不知道在函数声明时可能有多少参数,那么你可以声明不带形参的函数,并且可以通过函数调用时传递的参数数组访问所有变量。
推荐文章
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何禁用文本选择使用jQuery?
- 如何停止事件冒泡复选框点击
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 向对象数组添加属性
- 如何在Redux应用程序中动态加载代码分割的减速器?