0

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)```
1
  • unsolvedArray[0][1] or unsolvedArray[1][0] will be undefined in your case. Same goes for further indices. Try to use .push(). Commented Jun 15, 2021 at 19:45

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.