用于javascript的func_get_args

时间:2012-06-19 17:38:46

标签: javascript jquery

如何在数组中的javascript中获取所有函数参数?

function(a, b, c){

 // here how can I get an array of all the arguments passed to this function
 // like [value of a, value of b, value of c]
}

4 个答案:

答案 0 :(得分:10)

你想要arguments 数组对象。

function x(a, b, c){
    console.log(arguments); // [1,2,3]
}

x(1,2,3);

UPDATE arguments实际上不是一个数组,它是一个“类似数组的对象”。要创建一个真正的数组,请执行以下操作:

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

答案 1 :(得分:8)

您使用arguments对象(它不是数组,如其他答案中所述,它还有一些其他有趣的属性,请参阅 here)。 当您定义函数本身时,它会在函数的范围内自动创建。

functon bar(arg1,arg2,arg3,...)
{
     console.log(arguments[2]); // gets "arg2"'s value
}

还有另一种形式作为功能对象的属性:

function foo(a,b,c,d) {
}

var args = foo.arguments;

但是,虽然受到支持,但已被弃用。

答案 2 :(得分:5)

访问arguments对象。

function(a, b, c){
    console.log(arguments);
    console.log(arguments[0]);
    console.log(arguments[1]);
    console.log(arguments[2]);
}

答案 3 :(得分:5)

使用参数:

for (var i = 0; i < arguments.length; i++) {
  // arguments[i]
}