gpt4 book ai didi

javascript - 用 `let` 定义的变量如何在 `for` 循环中起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:57:00 25 4
gpt4 key购买 nike

<分区>

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 实例?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com