[英]Avoiding JSHint “function within in a loop” with Coffeescript closure inside of loop
[英]Function inside loop closure issue
我真的在努力理解閉包。 我只是寫了一個小函數來嘗試在數組索引中存儲多個函數,但是當我打印出來時它們是不確定的。
這是我的代碼:
function x() {
var arr = [];
for(var i = 0; i < 5; i++) {
arr.push( (function(index) { console.log(index) } )(i) );
}
return arr;
}
var z = new x();
for (var j = 0; j < 5; j++) {
console.log(z[j]); // Reads Undefined?
}
據我所知,我正在使用IIFE並傳入“ i”並將其用作“索引”,這應該使我繞過不斷打印出最后一個索引的已知封閉范圍問題。 但是,為什么我的數組索引未定義並且沒有打印出“ i”?
幫助將不勝感激。 謝謝。
您不會從IIFE返回任何內容,因此它隱式地返回undefined
,該值將追加到數組中。 如果要存儲index
值,則需要返回它:
arr.push( (function(index) { console.log(index); return index; } )(i) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.