I just dove into learning JavaScript and encountered an issue.
I whipped up a simple code that tallies elements within a nested array, but for some reason, the code malfunctions when adding an element to the first nested array. The cause of this problem eludes me.
var clothes = [
['cap', 'scarf'], //-- Inserting a new element here causes the counter to malfunction
['T-shirt', 'shirt', 'trousers'], //-- Adding new items here works without any issues
['boots', 'sneakers'] //-- Adding new items here also doesn't pose any problems
];
var totalItems = function () {
for (var i = 0; i < clothes.length; i++) {
var total = 0;
for (var k = 0; k <= clothes[i].length; k++) {
total = total + clothes[k].length;
}
return total
}
};
console.log('all clothes: ' + totalItems());
Error:
Uncaught TypeError: Cannot read property 'length' of undefined
at totalItems (test2.js:13)
at test2.js:31
Please provide assistance and elucidate why the error only occurs when modifying the first nested array.