-1
if(a == 1){
  parameter = ['1','true','a'];
}else{
  parameter = ['2','false','b'];
}

function run(a,b,c){

}

How can I pass an array as arguments to the function run? I tried JSON.Stingify but it doesn't work as I'm still seeing the array bracket in my console.log()

1983
  • 5,882
  • 2
  • 27
  • 39
Alice Xu
  • 533
  • 6
  • 20

3 Answers3

1

You can use javascript apply():

run.apply(this, parameter);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • wait, I mean pass the param as string. function run(a,b,c) only accept 3 string, not array. – Alice Xu Jul 22 '15 at 09:38
  • It will pass three strings as function arguments http://jsfiddle.net/zm0c3jhx/ Now if it isn't what you mean, edit your question with clearer expected behaviour – A. Wolff Jul 22 '15 at 09:39
0

Here are two options.

Call the function directly.

if(a == 1){
    run('1', 'true', 'a');
}else{
    run('2', 'false', 'b');
}

Or use Function.prototype.apply to call the function with an array as arguments.

if(a == 1){
    parameter = ['1','true','a'];
}else{
    parameter = ['2','false','b'];
}

run.apply(null, parameter);
1983
  • 5,882
  • 2
  • 27
  • 39
0

Just do it like this:

http://codepen.io/anon/pen/xGaWNr

Code

x = ['2','false','b'];

var run = function (x0,x1,x2) {
    document.write (x0+'<br>');
    document.write (x1+'<br>');
    document.write (x2+'<br>');
}

run(x[0],x[1],x[2]);

Output

2
false
b
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147