javascript - 'TypeError: 无法设置未定义的属性(设置 '0')'----数组赋值
当我在 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] 出错了;
有人知道为什么吗?谢谢。
答案#1
每当 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;
答案#2
正如评论所示,可以使用 .push。这就是我在我的情况下实现该解决方案的方法。
const myArray = [[]];
const height = 7;
const width = 8;
for (let i= 0; i < height; i++) {
if (i> 0) myArray.push([]); // this initialises the array.
for (let j = 0; j < width; j++) {
myArray[i][j] = "x";
}
}
console.log(myArray)
这是一个 codepen
