javascript - '类型错误: Cannot set properties of undefined (setting '0' )'----Array assignment

标签 javascript arrays typescript

当我在 Leetcode 上解决问题时,我定义了一个空数组。我尝试推送一些数字然后收到此错误。我不知道为什么。我的代码在这里。

        // r and c are already defined numbers,arr is already defined array.
        let n = [[]]
        let index = 0
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                    n[i][j] = arr[index]
                    index++;
            }
        }
        return n; 

Leetcode 告诉我 n[i][j] = arr[index] 有错误;

有人知道为什么吗?谢谢。

最佳答案

每当 i 的值变为 1 时,在内循环中就会将值设置为 n[i][j],即 n[1][0],这里 n[1] 是未定义的,它正在访问第0个索引值未定义,这就是错误的原因。

第一次迭代工作正常,因为第 0 个索引中已经有一个空数组(当 i = 0 时)。

在这里你可以尝试这样做

let n = []
let index = 0
for (let i = 0; i < r; i++) {
    n[i] = [];
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index];
        index++;
    }
}

return n;

关于javascript - '类型错误: Cannot set properties of undefined (setting '0' )'----Array assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71890694/

相关文章:

javascript - 通过 Maps Javascript 解析

c++ - 为什么动态分配的数组大小在插入时是初始数组的 2*size,而不是 size+1?

typescript - 如何重构类型注释?

php - ajax按钮加载状态

php - 有没有办法让 javascript 执行 php 命令?

javascript - 使用 Ajax 根据另一个下拉选项填充下拉列表

angular - 将 bool 值从 observable 传递到 observable

javascript - 在搜索比较中通过 jquery 在页面内排列搜索结果

java - 带有 BufferedImage 的 setRGB 提供不正确的着色

typescript - 有没有办法获得通用剩余参数的交集类型?