When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.
// 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 told me n[i][j] = arr[index] had error;
Anyone knows why? thanks.
When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.
// 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 told me n[i][j] = arr[index] had error;
Anyone knows why? thanks.
Share Improve this question edited May 6, 2022 at 7:32 Yin WeiLin CN asked Apr 16, 2022 at 2:48 Yin WeiLin CNYin WeiLin CN 231 gold badge1 silver badge5 bronze badges 2- 2 Here n[i][j] = arr[index] tries to get the element with index i and then assign the element of the inner array with the arr element. The problem is that your n array has only one element and hence n[i] is undefined where variable i is greater than 0 – Tanay Commented Apr 16, 2022 at 2:56
- 1 @Tanay thanks! I tried creating new Array to push some numbers ,then push Array to n . Now I can get the right two-dimensional array N. My code got ACCEPT! thanks you again! Have a nice day! – Yin WeiLin CN Commented Apr 16, 2022 at 3:19
2 Answers
Reset to default 4Whenever the value of i bees 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.
the first iteration works fine because there is already an empty array in the 0th index (when i = 0).
here you can try doing this
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;
As the ments showed, it is possible to use .push. This is how I implemented that solution in my case.
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)
Here is a codepen
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744224617a4563944.html
评论列表(0条)