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?
2 Answers 2
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)
answered Dec 30, 2020 at 7:22
Prashant Prabhakar Singh
1,2004 gold badges16 silver badges35 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Dec 30, 2020 at 7:23
kennysliding
3,0051 gold badge17 silver badges39 bronze badges
Comments
lang-js
varfor the arguments.function foo(x, y, z)works fine.