使用 let in 迴圈而不是 var(單擊處理程式示例)

假設我們需要為每個 loadedData 陣列新增一個按鈕(例如,每個按鈕應該是一個顯示資料的滑塊;為了簡單起見,我們只是提醒訊息)。有人可能會嘗試這樣的事情:

for(var i = 0; i < loadedData.length; i++)
    jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
        .children().last() // now let's attach a handler to the button which is a child
        .on("click",function() { alert(loadedData[i].content); });

但不是警報,每個按鈕都會導致

TypeError:loadedData [i]未定義

錯誤。這是因為 i 的範圍是全域性範圍(或​​函式範圍)和迴圈後的 i == 3。我們需要的不是“記住 i 的狀態”。這可以使用 let 來完成:

for(let i = 0; i < loadedData.length; i++)
    jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
        .children().last() // now let's attach a handler to the button which is a child
        .on("click",function() { alert(loadedData[i].content); });

使用此程式碼測試 loadedData 的示例:

    var loadedData = [
        { label:"apple",      content:"green and round" },
        { label:"blackberry", content:"small black or blue" },
        { label:"pineapple",  content:"weird stuff.. difficult to explain the shape" }
    ];

一個小提琴來說明這一點