当我在 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/