<分区>
在documentation for the let
statement in MDN ,有这个示例代码:
var list = document.getElementById("list");
for (let i = 1; i <= 5; i++) {
let item = document.createElement("li");
item.appendChild(document.createTextNode("Item " + i));
item.onclick = function (ev) {
console.log("Item " + i + " is clicked.");
};
list.appendChild(item);
}
然后他们说:
The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of the variable i.
我不明白为什么有“变量 i
的五个不同实例。
for
循环中的第一条语句总是执行一次,不是吗?
所以 let
语句应该只执行一次...
一旦代码到达迭代的末尾,它就会检查第二条语句中的条件。
为什么,根据他们写的,每次迭代都有一个新的 i
实例?