问题:
var funcs = []; // let's create 3 functions for (var i = 0; i < 3; i++) { // and store them in funcs funcs[i] = function() { // each should log its value. console.log("My value: " + i); }; } for (var j = 0; j < 3; j++) { // and now let's run each one to see funcs[j](); }
It outputs this: 它输出:
My value: 3 我的价值:3
My value: 3 我的价值:3
My value: 3 我的价值:3
Whereas I'd like it to output: 而我希望它输出:
My value: 0 我的值:0
My value: 1 我的价值:1
My value: 2 我的价值:2
The same problem occurs when the delay in running the function is caused by using event listeners: 当由于使用事件侦听器而导致功能运行延迟时,会发生相同的问题:
var buttons = document.getElementsByTagName("button"); // let's create 3 functions for (var i = 0; i < buttons.length; i++) { // as event listeners buttons[i].addEventListener("click", function() { // each should log its value. console.log("My value: " + i); }); }
<button>0</button> <br /> <button>1</button> <br /> <button>2</button>
… or asynchronous code, eg using Promises: …或异步代码,例如使用Promises:
// Some async wait function const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms)); for (var i = 0; i < 3; i++) { // Log `i` as soon as each promise resolves. wait(i * 100).then(() => console.log(i)); }
What's the solution to this basic problem? 这个基本问题的解决方案是什么?
解决方案:
参考一: https://stackoom.com/question/39Ec/循环内的JavaScript闭合-简单的实际示例参考二: https://oldbug.net/q/39Ec/JavaScript-closure-inside-loops-simple-practical-example
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4296333