Home > Blockchain >  The Logic of forEach() when works with variables in javascript?
The Logic of forEach() when works with variables in javascript?

Time:10-30

the result of code is :

test0: apple
1: orange
2: cherry

I want to know why my text variable is equal to "" in second and third loop, I expected the previous values to be added to the initial value of the text variable, Can anyone explain what happens to the text variable and what is the logic of forEach in this example ?

let text = "test";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text  = index   ": "   item   "<br>";
}
<p id="demo"></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your loop runs such that the text test is only added once. In the beginning and then later the variable text is updated.

If you want to add in every iteration just keep it in a seperate variable and keep adding.

let text = "";
let test = "test";

const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text = text   test   index   ": "   item   "<br>";
}
<p id="demo"></p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your codes works as expected. using innerText rather than innerHTML might illuminate the situaion

let text = "test";
const fruits = ["apple", "orange", "cherry"];
//fruits.forEach(myFunction);

document.getElementById("demo").innerText = text;

function myFunction(item, index) {
  text  = index   ": "   item   "<br>";
  document.getElementById("demo").innerText = text;
  console.log(item,index);
}

window.setTimeout( myFunction.bind(null,fruits.shift(),0), 1000);
window.setTimeout( myFunction.bind(null,fruits.shift(),1), 2000);
window.setTimeout( myFunction.bind(null,fruits.shift(),2), 3000);
<p id="demo"></p>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related