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

标签 javascript iteration

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

(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/

相关文章:

PHP/JSON - stdClass 对象

python - 在遍历集合时修改集合

Python - 同时遍历两个列表而不在每次迭代中都移动到下一行

javascript - 减少很多require()函数

javascript - 评估中的异常

python - itertools.chain() 是否允许从消耗的项目中释放内存

python - 嵌套循环: representing factors of numbers up to 20 graphically

javascript - 如何将字符串数组转换为 javascript 中的对象属性?

javascript - 为什么 Jest 测试中不调用此函数?

Javascript 在 HTML 中没有 script 标签的情况下工作?