pass a variable to foreach function

雨燕双飞 提交于 2021-02-16 15:53:10

问题


Hi I want pass antwoord to

opleidingArray.forEach(haalScoresOp, antwoord);

So I can use it in the

HaalScoresOp

function. I cannot get this to work. I also tried binding but this does not function.

I am getting antwoord is not defined as an error.

var antwoordenPerVraag = [2,1,3];

console.log(VragenEnScores.vragen[0].opleidingen[0]);


antwoordenPerVraag.forEach(berekenEindresultaten);

function berekenEindresultaten(item, index) {
  var opleidingArray = VragenEnScores.vragen[index].opleidingen;

  var antwoord = "bla";

  opleidingArray.forEach(haalScoresOp, antwoord);
  // score nog doorgeven aan haalscores op = het item
}

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

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

回答1:


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));



回答2:


You can simply use :

opleidingArray.forEach(haalScoresOp, antwoord);

And refer to antwoord inside the haalScoresOp function as follow:

function haalScoresOp(){
    var diantwoord = this.valueOf();
}

antwoord is passed as 'this' object to the function regarding the type




回答3:


You could change the haalScoresOp function to be an anonymous function inside the berekenEindresultaten function:

var antwoordenPerVraag = [2,1,3];

console.log(VragenEnScores.vragen[0].opleidingen[0]);

antwoordenPerVraag.forEach(berekenEindresultaten);

function berekenEindresultaten(item, index) {
  var opleidingArray = VragenEnScores.vragen[index].opleidingen;

  var antwoord = "bla";

  opleidingArray.forEach(function(item, index){
    // score nog doorgeven aan haalscores op = het item
    console.log("haal score op voor");
    console.log(item.naam);
    console.log(item.scores);

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

}

This would keep the scope of the antwoord variable inside the berekenEindresultaten function



来源:https://stackoverflow.com/questions/39144210/pass-a-variable-to-foreach-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!