i'm a girl
i'm a girl

Reputation: 328

JS pass array values as separate arguments

I have a CSV file of some data and for each line, I split it by the comma to get an array vals.

Now I want to pass vals into a function, but "flatten" it (without changing the function because it is used elsewhere)

function foo(x, y, z) {
     return x*y*z:
}
    
var vals = [1, 3, 4];
//want a shortcut to this (this would be a nightmare with like 20 values)
foo(vals[0], vals[1], vals[2]);

Edit:
Sorry, kind of left out a big detail. I only want part of the array, like the first 10 elements of a 12 element array. Any shortcut for this?

Upvotes: 2

Views: 634

Answers (2)

kennysliding
kennysliding

Reputation: 2985

first you don't need var in the parameters,

second, you may use the spread operator

function foo(x, y, z) {
  return x * y * z;
}
var vals = [1, 3, 4];
console.log(foo(...vals));

reference: spread operator

Upvotes: 0

Prashant Prabhakar Singh
Prashant Prabhakar Singh

Reputation: 1190

Use Spread operator; if you are using es6.

var vals = [1,2,34,5]
foo(...vals)

Or you could also use apply

function foo(a,b,c,d,e) {
  console.log(a,b,c,d,e)
}
var vals = [1,2,3,4,5]
foo.apply(null, vals)

Upvotes: 4

Related Questions