gpt4 book ai didi

javascript - 为什么这个迭代永远有效

转载 作者:行者123 更新时间:2023-12-04 08:09:14 25 4
gpt4 key购买 nike

为什么这段代码运行无限时间。
我不明白发生了什么。

(function(){
console.log("Start")

function add(){
s.delete(add); //When I delete this line, everything works fine.
s.add(add);
console.count("run")
}

const s = new Set([
add
]);

s.forEach(value => {
value()
});

console.log("Finish")
})()
这是一个概览代码。

最佳答案

对此的答案在 Set.prototype.forEach 的规范中:

Each value is normally visited only once. However, a value will berevisited if it is deleted after it has been visited and then re-addedbefore the forEach call completes. Values that are deleted after thecall to forEach begins and before being visited are not visited unlessthe value is added again before the forEach call completes. New valuesadded after the call to forEach begins are visited.


由于它是一个您不断添加和运行的功能,因此它会继续这样做,删除并再次添加它。因此,您创建了一个无限循环。

关于javascript - 为什么这个迭代永远有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065666/

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