I have an array which elements are also arrays, each containing 3 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()?
解决方案
First, calcMe doesn't seem to return a function, so you can't pass its return value to forEach.
I'm guessing you want something like
var arr = [
[1, 5, 4],
[8, 5, 4],
[3, 4, 5],
[1, 2, 3]
]
function calcMe(a, b, c) {
var pre = document.getElementById('pre')
pre.innerHTML += 'calcMe arguments: ' + a +","+ b +","+ c + "
";
}
arr.forEach(function(el, index) {
// Could also use `arr[index]` instead of el
calcMe.apply(this, el);
});
For a fancier version, you can bind Function.prototype.apply to emulate creating a function like I did above.