简体   繁体   中英

Javascript closures - understanding for loop

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i); });
  document.body.appendChild(btn);
}

In the above code - the output will be 5 always no matter what button is pressed because I understand in js it is by referene, by the time the loop completed the final value will be updated in to 'i' - but 1 question I have is why 5 - I thought it is 4 - once the value of i is 4 shouldn't it come out of the loop?? Am I missing some understanding with 'for' loops?

Your question is not about the closure, but rather about the loop, right? The closure is a different story, but the loop is straightforward - it does the increment step before checking to see if it passes the conditional:

The order is:

  • Initialize i to 0
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 1
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 2
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 3
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 4
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 5
  • _
  • Check to see if i < 5 (it is not)
  • End the loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM