调用具有可变参数长度的函数

时间:2011-05-25 20:25:53

标签: javascript

  

可能重复:
  How to create a function and pass in variable length argument list?

我想用可变参数列表

调用console.log
console.log("a","b")
console.log("a","b","c")

但我从数组中获取参数:

var arr = ["a","b","c"];

我希望传递单个变量而不是完整数组。 所以console.log(arr)不是我想要的,console.log(arr[0],arr[1],arr[2])也很糟糕,因为我不知道c的数组长度。

我该怎么做?

console.log只是一个例子,我会在不同的问题中使用它


更新

How to create a function and pass in variable length argument list? 不好。因为根据答案

function dump(a,b) {
  console.log("a:"+a,"b:"+b);
}

var asd = [1,2,3]

dump.call(this,asd)

应该提供输出:a:1,b:2而不是a:[1,2,3] b:undefined


更新:

也许我的问题不够清楚,抱歉。

console.log只是一个示例的变量参数调用

我想对不同的问题

使用相同的方法

看看这个例子:

function Sum() {
  var temp = 0;
  for(var i=0;i<arguments.length;++i) {
     temp+= arguments[i];
  }
  return temp;
}

我希望使用数组中的不同参数调用。

var test1 = [1,2,3];
var test2 = [4,5,6];

var a = Sum.call(this,test1) //this gives an output "01,2,3"

var b;
for(var i=0;i<test2.length;++i) {
  b = Sum(test2[i])
} //this is also bad because it only returns 6 at the last invoke.

4 个答案:

答案 0 :(得分:7)

使用Function.apply

console.log.apply(console, arr);

这回答了你问的问题。如果您打算问:

  

为什么dump.call(this,asd)会产生“a:[1,2,3] b:undefined”的输出?

答案(任何文档都会告诉你)是Function.call是可变参数,第一个之后的任何参数都传递给函数,而Function.apply只接受两个参数:{的值{应用函数中的{1}}和传递给函数的参数数组。

换句话说,this相当于:

Function.call

答案 1 :(得分:3)

答案 2 :(得分:2)

根据您的更新,此修改将起作用:

function dump(a,b) {
  console.log("a:"+a,"b:"+b);
}

var asd = [1,2,3]

dump.apply(this,asd)

请注意,您需要使用“apply”而不是“call”。 但是你的函数决定输出多少个参数(console.log(“a:”+ a,“b:”+ b)),所以它的价值有限。你可以试着清楚解释为什么console.log.apply(console,asd)没有给你你想要的东西吗?

答案 3 :(得分:0)

不确定你的意思......但javascript是一个动态的语言,你可以传递动态对象。所以你可以这样做:

  

var obj = {0:“a”,1:“b”,2:“c”};   的console.log(OBJ);

对象'obj'可以包含您需要的任意数量的属性,并且可以作为单个参数传递给任何函数。