PHP中有func_num_args和func_get_args, JavaScript中也有类似的东西吗?


当前回答

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

var args = Array.slice(arguments)

否则:

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

来自Mozilla MDN:

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

其他回答

对于现代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允许使用“…”符号指定函数参数的构造,例如

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

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

var args = Array.slice(arguments)

否则:

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

来自Mozilla MDN:

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

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

希望这能有所帮助:

function x(...args) {
    console.log( {...[...args] } ); 
}

x({a:1,b:2}, 'test');

输出:

{ '0': { a: 1, b: 2 }, '1': 'test' }