[Tip] How to pass an array as an argument to a function.

| No Comments »

Problem: Help! Iis it possible to pass the values of an array as an argument in my function?

Anwer: Conveniently, Yes! You can indeed use set an array as the argument of a function.

var mapArgs = [0,20,50,10];
draw.apply(this, mapArgs);

function draw(x1,x2,y1,y2)
{ // do something…
alert(x1 + ‘ ‘ + x2 + ‘ ‘ + +y1 + ‘ ‘+ y2);
}

Of course you can use it in a more creative way

var run = { ready : ["Is this awesome?"], getset : ["or…"], go: ["What?!"] }
var func = {
ready: function(str)
{
alert(str);
},
getset: function(str)
{
alert(str.toUpperCase());
},
go: function(str)
{
alert(str + ‘!!!’);
}
}

for (x in run)
func[x].apply(this, run[x]);



Leave a Reply