JavaScript:
I am trying to populate an array.
var blocks = [];
var blocksCount = 7;
for (var columnIndex = 0; columnIndex < blocksCount; columnIndex++) {
for (var rowIndex = 0; rowIndex < blocksCount; rowIndex++) {
blocks[columnIndex][rowIndex] = 'Some Value';
}
}
The error message says: undefined is not an object!
What do I have to change to make it work?
4 Answers 4
You have to assign an array to blocks[columnIndex] before you try to assign a value to a property of that array.
blocks[columnIndex] is not defined when you are assigning a value to the rowIndex on it. You cannot assign a value to something that is not defined yet. Hence, define columnIndex as an empty array when it is not defined yet i.e for the first time. You can do like this,
blocks[columnIndex] = blocks[columnIndex] || [];
var blocks = [];
var blocksCount = 7;
for (var columnIndex = 0; columnIndex < blocksCount; columnIndex++) {
blocks[columnIndex] = blocks[columnIndex] || [];
for (var rowIndex = 0; rowIndex < blocksCount; rowIndex++) {
blocks[columnIndex][rowIndex] = 'Some Value';
}
}
console.log(blocks);
Currently, you do not have a multidimensional array.
var arr = [];
console.log(arr[0]);
Will return undefined and you are attempting to assign new elements at this point.
You can overcome this and create a multidimensional array within your first for loop statement and create a new array within the original blocks array.
blocks[columnIndex] = [];
You can then assign both values to the multidimensional array.
var blocks = [];
var blocksCount = 7;
for (var columnIndex = 0; columnIndex < blocksCount; columnIndex++) {
blocks[columnIndex] = [];
for (var rowIndex = 0; rowIndex < blocksCount; rowIndex++) {
blocks[columnIndex][rowIndex] = 'Some Value';
console.log(blocks[columnIndex][rowIndex]);
}
}
Comments
You can use the from constructor of an Array to pass a function into the array creation. This means no need for for loops :)
const blockCount = 7;
const block = Array.from({ length: blockCount }, (_, i) => {
return Array.from({ length: blockCount }, (_, j) => 'Some Value');
});
console.log(block);
Cannot set property '0' of undefined.