有个循环,循环一个异步回调,为啥回调引用的循环值都是最后一步循环的循环值?然后,又有些时候无论什么循环值都得不到?
1 var arr = [1,3,5,7,9]; 2 var arrLength = arr.length; 3 4 for (var i = 0; i < arrLength; i++) { 5 setTimeout(function() { 6 console.log(i); 7 console.log(arr[i]); 8 }, 2000); 9 }
结果是:
5 undefined 5 undefined 5 undefined 5 undefined 5 undefined
解决方法:使用自执行函数传参
1 var arr = [1,3,5,7,9]; 2 var arrLength = arr.length; 3 4 for (var i = 0; i < arrLength; i++) { 5 (function(i) { 6 setTimeout(function() { 7 console.log('i是' + i); 8 console.log('value是' + arr[i]); 9 }, 2000); 10 })(i); 11 }
结果是:
i是0
value是1
i是1
value是3
i是2
value是5
i是3
value是7
i是4
value是9
参考链接:
https://www.jianshu.com/p/690f58a3ff7b