Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach() and Apply() methods for two dimensional array in JavaScript

I have an array whose elements are also arrays, each containing three elements. I want to call the function calcMe(a,b,c){...} for each of the elements of my main array using forEach() method, but I got really confused and don't know how to get it to work.

arr = [[1,5,4], [8,5,4], [3,4,5], [1,2,3]]
function calcMe(a,b,c){...}
arr.forEach(calcMe.Apply(-----, -----));

How do I pass each of the inner array's elements as arguments to my function using Apply()?

like image 304
jacqui_g Avatar asked Jul 21 '26 05:07

jacqui_g


1 Answers

apply calls a function immediately, so you can't use it directly because forEach expects a function reference. However, you can use bind on apply to achieve what you want:

arr.forEach(Function.apply.bind(calcMe, void 0));

The second argument will be the this value. You can provide whatever value instead of void 0.

var arr = [[1,5,4],[8,5,4],[3,4,5],[1,2,3]];
function calcMe(a,b,c){
  document.querySelector('pre').textContent += [a,b,c] + '\n';
}
arr.forEach(Function.apply.bind(calcMe, void 0));
<pre></pre>
like image 54
Oriol Avatar answered Jul 22 '26 17:07

Oriol