首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何修复for..in循环中的“未捕获的ReferenceError”

如何修复for..in循环中的“未捕获的ReferenceError”
EN

Stack Overflow用户
提问于 2019-09-05 10:50:09
回答 3查看 294关注 0票数 0

当我使用for..of循环时,当我试图运行它时,迭代器的值抛出一个"ReferenceError“。

我曾尝试将for...of循环更改为for...in循环,但无济于事。我怀疑这与标记为模块的脚本有关,或者可能是我的utils.js文件,但我删除了它们,仍然得到相同的服务器。我在Windows 10上的Chrome 76上遇到了这个错误。

代码如下:

代码语言:javascript
运行
复制
<body>
    <canvas id="canvas" width="800" height="600">
        Bruh. are you using IE?!
    </canvas>
    <script type="module">
        import { Mouse, Screen } from "./utils.js"

        let attractionForce = 1;
        let friction = 0.99;

        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        //let mouse = new Mouse(canvas);
        const PI_2 = Math.PI * 2;

        var points = Array.from({ length: 1000 }, () => ({
            x: Math.random() * 800,
            y: Math.random() * 600,
            dx: (Math.random() - 0.5),
            dy: (Math.random() - 0.5),
        }));

        for (pti of points) console.log(pti); << Uncaught ReferenceError: pti is not defined
    </script>
</body>

通常,它只是在循环上迭代,但现在它抛出了一个错误。任何帮助都将不胜感激!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-09-05 11:12:15

type="module" use strict mode automatically的脚本。因此,因为在使用之前没有定义pti,所以会出现引用错误。

显然,解决办法是确保定义了pti。您可以将其声明为for.. in循环中的变量,但必须在启动for...of循环之前声明它,因为后者的语法不支持控制结构中的变量定义。

如果不调用严格模式,模块类型脚本元素之外的代码求值将不会重现错误。

票数 2
EN

Stack Overflow用户

发布于 2019-09-05 10:54:13

可能缺少pti的声明

尝试将for (pti of points) console.log(pti);更改为for (let pti of points) console.log(pti);

票数 1
EN

Stack Overflow用户

发布于 2019-09-05 11:05:34

您可以在chrome开发工具中尝试这段代码。

代码语言:javascript
运行
复制
 var points = Array.from({ length: 1 }, () => ({
     x: Math.random() * 800,
     y: Math.random() * 600,
     dx: (Math.random() - 0.5),
     dy: (Math.random() - 0.5),
 }));

enter image description here

无密钥pti

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57797809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档