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:
i
to 0i < 5
(it is)i
to 1i < 5
(it is)i
to 2i < 5
(it is)i
to 3i < 5
(it is)i
to 4i < 5
(it is)i
to 5i < 5
(it is not)
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.