Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a variable to foreach function

Hi I want pass the var antwoord to

opleidingArray.forEach(haalScoresOp, antwoord);

So I can use it in the function HaalScoresOp

var antwoordenPerVraag = [2,1,3];

function haalScoresOp(item, index) {
  console.log("haal score op voor");
  console.log(item.naam, item.scores);

  console.log("haal antwoord op", antwoord);
}    

function berekenEindresultaten(item, index) 
{
  var opleidingArray = VragenEnScores.vragen[index].opleidingen;
  var antwoord = "bla";
  opleidingArray.forEach(haalScoresOp, antwoord);
}

antwoordenPerVraag.forEach(berekenEindresultaten);
  • I tried binding but this does not function.
  • I am getting antwoord is not defined as an error.
like image 484
Christoph Avatar asked Aug 25 '16 11:08

Christoph


People also ask

How can I get data outside a forEach loop in JavaScript?

Just use the array outside of data.

Does forEach require return?

The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself. So it's not chainable like those other methods are.

Can you break out of forEach?

From the official MDN docs: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.


1 Answers

The way you're referencing antwoord inside haalScoresOp is invalid/nonsense/not good. You're referencing it as if it was a variable in scope… well, it's not. The function should accept it as parameter just like its other parameters:

function haalScoresOp(antwoord, item, index) {
  ..
  console.log(antwoord);
}

Then you can pass it in on the caller's side:

opleidingArray.forEach(function (item, index) {
    haalScoresOp(antwoord, item, index)
});

or:

opleidingArray.forEach(haalScoresOp.bind(null, antwoord));
like image 138
deceze Avatar answered Oct 08 '22 05:10

deceze