javascript - 在 javascript 中使用二维数组并尝试从中读取值给出 "Uncaught TypeError: Cannot read property ' 0' of undefined"

标签 javascript jquery html arrays

我正在尝试使用值在 html Canvas 上穿过迷宫。 我创建了一个二维数组,其中包含值。

const pot=[[0, 2], [-2, 0], [0, 1], [-1, 0], [0, 2], 
    [1, 0], [0, 3], [1, 0], [0, 1], [1, 0], 
    [0, -1], [2, 0], [0, -1], [1, 0], [0, 1], 
    [4, 0], [0, -1], [-3, 0], [0, -1], [3, 0], 
    [0, -2], [2, 0], [0, 3], [-1, 0], [0, 1], 
    [1, 0], [0, 1], [-1, 0], [0, 1], [-1, 0], 
    [0, -1], [-6, 0], [0, 2], [1, 0], [0, 2], 
    [1, 0], [0, 1], [-1, 0], [0, -1], [-1, 0], 
    [0, -2], [-1, 0], [0, 1], [-5, 0], [0, -1], 
    [1, 0], [0, -1], [-1, 0], [0, -1], [2, 0], 
    [0, -1], [-1, 0], [0, -1], [-2, 0], [0, 4], 
    [-2, 0], [0, -1], [1, 0], [0, -1], [-2, 0], 
    [0, 3], [2, 0], [0, 2], [-1, 0], [0, -1], 
    [-1, 0], [0, 2], [3, 0], [0, -2], [2, 0], 
    [0, 1], [-1, 0], [0, 3], [-1, 0], [0, 1], 
    [4, 0], [0, -1], [-2, 0], [0, -1], [5, 0], 
    [0, 1], [-2, 0], [0, 1], [2, 0], [0, 1]];

为了从中读取值,我做了一个for循环

var dolz=pot.length;
    for(var i=0; i<=dolz; i++){
        x += pot[i][0]*(w/dimenzija);
        y += pot[i][1]*(h/dimenzija);
        ctx.lineTo(x, y);
    }
    ctx.stroke();

当我运行代码时,出现错误 Uncaught TypeError: Cannot read property '0' of undefined ,该错误引用 jquery 库,然后返回 for 循环代码并指出错误在 x += pot[i][0]*(w/dimenzija); 代码的一部分。此错误的原因可能是什么?

最佳答案

将“<=”更改为“<”。 数组的长度始终大于数组中的最后一个索引。

关于javascript - 在 javascript 中使用二维数组并尝试从中读取值给出 "Uncaught TypeError: Cannot read property ' 0' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421914/

相关文章:

javascript - TypeScript 构建错误 : Property does not exist on type 'IStateParamsService'

javascript - 如果选中任何复选框,则另一个 div 将被 fadeIn();

javascript - 在打印 div 上包含 css 样式

javascript - 获取 html 表单值

jquery - 如何在订单中执行ajax成功回调?

php - 使用 CSS 在现有内容后面的网页上显示背景图片

javascript - 如何使用 Angular 为 js-calendar-year 中的每个选定日期添加颜色。页面刷新后颜色应该保持不变

javascript - 在隐藏字段数组中添加和删除值,无需提交表单

javascript - 如何将 php 元素转换为 javascript

jquery - 用于搜索所需模态窗口的脚本(通过 Id 按钮)(不起作用)