Javascript - как правильно заполнить двумерный массив объектами?
this.objectsArr = []; // Массив объектов
this.objectsArr[0]=[]; //сделал двумерным
this.coordsSquare = [];
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const width = 70;
const height = 70;
const x = i * 80 + 10;
const y = j * 80 + 10;
const square = this.generateSquare({
x, y, width, height, i, j
});
this.coordsSquare.push(square);
this.objectsArr[i,j] = square; //добавление в него
}
}
В итоге в массиве вместо 81 объекта всего 9.
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Как-то так хотели?
Двумерный массив это массив массивов, а у вас массив this.objectsArr[i,j] - это обращение к элементу j массива this.objectsArr.
Обычно создается одномерный массив и в ячейку каждого пушится другой массив.
результат i,j от 0,0 до 8,8 Можно подсчитать там 81
this.objectsArr = []; // Массив объектов
for (let i = 0; i < 9; i++) {
this.coordsSquare = new Array();
for (let j = 0; j < 9; j++) {
const width = 70;
const height = 70;
const x = i * 80 + 10;
const y = j * 80 + 10;
//const square = this.generateSquare({
// x, y, width, height, i, j
//});
const square = {x, y, width, height, i, j}
this.coordsSquare.push(square);
}
this.objectsArr.push(coordsSquare); //добавление в него
}
console.log(objectsArr);
а обращение по типу a[i,j] даст значение массива a под индексом j можно посмотреть на пример
let array = [1,2,3,4,5,6,7,8];
console.log(array[1,5])
let index = (1,5);
console.log(index)
Есть очень хороший пример связанный с запятой
let sum = (1 + 1,5); // тут 2 операции 1 + 1 и 5
console.log(sum);