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

其他回答

如果您愿意,还可以将其转换为数组。如果Array泛型可用:

var args = Array.slice(arguments)

否则:

var args = Array.prototype.slice.call(arguments);

来自Mozilla MDN:

您不应该对参数进行切片,因为这会阻止在 JavaScript引擎(例如V8)。

希望这是有用的代码:

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