The following code looks at a grid layout of elements and is designed to track the height of each element.
let columns = document.getElementsByClassName('_3Rcdf');
let cellHeights = new Array(columns);
for (let j=0; j<columns.length; j ) {
for (let i=0; i<columns[j].children.length; i ) {
cellHeights[j] = new Array(columns[j].children[i].length);
}
}
for (let k=0; k<cellHeights.length; k ) {
for (let i=0; i<columns[k].children.length; i ) {
cellHeights[k].push(columns[k].children[i].clientHeight);
}
}
Ideally what console.log(cellHeights)
should return is:
The expected output would be
cellHeights = [
[333, 372, 333],
[333, 333],
[372, 352]
]
But what my code actually returns is:
cellHeights = [
[undefined, 333, 372, 333],
[undefined, 333, 333],
[undefined, 372, 352]
]
I have figured out the problem is in this line:
cellHeights[j] = new Array(columns[j].children[i].length);
What this is doing is creating 3 arrays inside the cellHeights
array which are empty, thus the undefined. I think I need to immediately populate the arrays as they are created but I am not sure how to do so. Any suggestions?
CodePudding user response:
Don't initialize the array with a length.
push
ing into an array like that just adds them at the end of the array, even if the entries aren't actually filled with values:
const newArr = new Array(1);
console.log(newArr);
newArr.push(42);
console.log(newArr);
Instead of:
cellHeights[j] = new Array(columns[j].children[i].length);
Just assign an empty array:
cellHeights[j] = [];