为什么这段代码运行无限时间。 我不明白发生了什么。
(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 be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Values that are deleted after the call to forEach begins and before being visited are not visited unless the value is added again before the forEach call completes. New values added after the call to forEach begins are visited.
由于这是一个您不断添加和运行的函数,因此它会不断执行此操作,删除并再次添加回来。因此,您创建了一个无限循环。
关于javascript - 为什么这个迭代永远有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065666/