Problem:
In the code below, I continue to get an error of TypeError: Cannot read properties of undefined (reading '0')
for the conditional statement of the while loop.
var testObj = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9
};
var testArr = [
[1, []],
[2, []],
[3, []],
[4, []],
[5, []],
[6, []],
[7, []],
[8, []],
[9, []]
];
(_ => {
for (let x in testObj) {
let i = 0;
while (x !== testArr[i][0]) {
i++;
}
testArr[i][1].push(x);
}
})();
To explain how the code works, the anonymous function is supposed to iterate over each item in the object. During each iteration, the while loop will be used to find the array within the nested array for which the first data point (index 0) is the number that matches the current data point of the object, and then push that data point into the empty array located at index 1 in that array.
(This is a simplified version of a larger program for testing purposes. I am aware that the code is superfluous due to all numbers being ordered, but in the main program that won’t be the case.)
However, the program crashes upon entering the while loop due to the above mentioned type error.
I have confirmed that this is not a scope issue, as I can access the array from inside the while loop. I have also confirmed that a hard call to any of the data points in the nested array also works, so I don’t believe it is a syntax error. The only possible reason for the problem I can think of is that i
is somehow not a number by the time it is used in the while loop, but I have no idea how that could be happening.
Solution:
- In your
while
loop, you are not checking for the condition wheni
exceeds the size of the array. It is looking fortestArr[9]
which will beundefined
because there are only 8 elements intestArr
. - Why is it going to the 9th index you may ask- Because Keys in javascript objects can only be strings. Hence you are comparing string
'1'
with integer1
which results in false and hence the loop keeps incrementing.
You can either change the !==
to a !=
or convert the string keys to integer ones –
(_ => {
for (let x in testObj) {
let i = 0;
while (x != testArr[i][0]) {
i++;
}
testArr[i][1].push(x);
}
})();
(_ => {
for (let x in testObj) {
// Convert string to int
x = parseInt(x);
let i = 0;
while (x !== testArr[i][0]) {
i++;
}
testArr[i][1].push(x);
}
})();