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()?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With