I'm trying to set 100 values in a multidementional array to 1 (10x10) but im getting the error
TypeError: Cannot set property '0' of undefined
How can I fix this?
var unsolvedArray = [[]];
for (let i = 0; i < width; i++) {
for (let j = 0; j < width; j++) {
unsolvedArray[i][j] = 1;
}
}
console.log(unsolvedArray)```
asked Jun 15, 2021 at 19:32
Samuel Marchetti élève
153 bronze badges
-
unsolvedArray[0][1] or unsolvedArray[1][0] will be undefined in your case. Same goes for further indices. Try to use .push().Tushar Shahi– Tushar Shahi2021年06月15日 19:45:44 +00:00Commented Jun 15, 2021 at 19:45
1 Answer 1
unsolvedArray[0][1] or unsolvedArray[1][0] will be undefined in your case. Same goes for further indices. Try to use .push().
Using your own code:
var unsolvedArray = [];
for (let i = 0; i < width; i++) {
unsolvedArray.push([]); //This is adding the empty array, otherwise unsovledArray[0] will cause error.
for (let j = 0; j < width; j++) {
unsolvedArray[i].push(1); //Same logic, unsolvedArray[0][0] will cause error
}
}
answered Jun 15, 2021 at 19:46
Tushar Shahi
21.6k2 gold badges25 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js