PHP中有func_num_args和func_get_args, JavaScript中也有类似的东西吗?
当前回答
正如许多人指出的那样,参数包含传递给函数的所有参数。
如果您想调用另一个具有相同参数的函数,请使用apply
例子:
var is_debug = true;
var debug = function() {
if (is_debug) {
console.log.apply(console, arguments);
}
}
debug("message", "another argument")
其他回答
正如许多人指出的那样,参数包含传递给函数的所有参数。
如果您想调用另一个具有相同参数的函数,请使用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);
希望这是有用的代码:
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');
~拉胡尔·达克什
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允许使用“…”符号指定函数参数的构造,例如
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 非递归深度优先搜索算法
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 函数应该返回空对象还是空对象?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?