在 PHP 中有func_num_args和func_get_args,JavaScript 有没有类似的东西?
是否可以将函数的所有参数作为该函数内的单个对象获取?
IT技术
javascript
algorithm
function
arguments
marshalling
                    2021-02-10 09:32:20
                
                    
                
            
        6个回答
            使用arguments. 您可以像访问数组一样访问它。使用arguments.length的参数的数目。
所述参数是类似阵列的对象(不是实际的阵列)。示例函数...
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]); 
}
的arguments对象是函数的参数的存储位置。
arguments 对象的行为和看起来像一个数组,它基本上是,它只是没有数组所做的方法,例如:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.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 === Object {}
>value === two
>value === 3
如果您愿意,也可以将其转换为数组。如果 Array 泛型可用:
var args = Array.slice(arguments)
否则:
var args = Array.prototype.slice.call(arguments);
来自Mozilla MDN:
您不应该对参数进行切片,因为它会阻止 JavaScript 引擎(例如 V8)中的优化。