Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  113] [ 6]  / answers: 1 / hits: 23988  / 9 Years ago, tue, january 12, 2016, 12:00:00

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()?


More From » arrays

 Answers
9

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 + <br/>;
}

arr.forEach(function(el, index) {
// Could also use `arr[index]` instead of el
calcMe.apply(this, el);
});

<pre id='pre'></pre>





For a fancier version, you can bind Function.prototype.apply to emulate creating a function like I did above.


[#63754] Sunday, January 10, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnaj

Total Points: 490
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
johnnaj questions
Wed, May 4, 22, 00:00, 2 Years ago
Wed, Sep 22, 21, 00:00, 3 Years ago
Thu, May 20, 21, 00:00, 3 Years ago
Thu, Oct 8, 20, 00:00, 4 Years ago
;