var clothes = [
['cap', 'scarf'], //-- When adding a new element, the counter breaks
['T-shirt', 'shirt', 'trousers'], //-- When adding a new item, the counter works fine
['boots', 'sneakers'] //-- When adding a new item, the counter works fine
];
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());
未捕获的类型错误:无法读取未定义的属性“长度”
在 totalItems (test2.js:13)
在 test2.js:31
请帮忙解释为什么只有添加到第一个嵌套数组时才会出现错误?
答案 0 :(得分:0)
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
}
};
就这样编辑你的代码。似乎你的第二个条件查找不存在的索引。
答案 1 :(得分:0)
你有几个问题。您的 for 循环需要检查 < clothes.length
,因为 <=
将检查不在您的数组中的额外值(数组是基于 0 的,array.length 是基于 1 的)。您还每次通过 for 循环重新分配总数,并且在通过循环后从 for 循环返回。每次创建将急剧增长的数字时,您的内部循环也会不断增加 total 的值。
此修改将以更简洁的方式解决所有这些问题。
var totalItems = function () {
var total = 0;
for (var i = 0; i < clothes.length; i++) {
total += clothes[i].length;
}
return total;
};
ES6 方式:
let totalItems = () => {
let total = 0;
clothes.forEach(entry => total += entry.length);
return total;
}
答案 2 :(得分:0)
您可以使用迭代器,每次函数在嵌套数组中找到新值时都会加 1 (iterator++)。在下面的示例中,我使用 forEach 嵌套在另一个 forEach 循环中。
var clothes = [
['cap', 'scarf', 'hat'], //-- Added a new element no breaky
['T-shirt', 'shirt', 'trousers'], //-- When adding a new item, the counter works fine
['boots', 'sneakers'] //-- When adding a new item, the counter works fine
];
var totalItems = function() {
let total = 0 //<-- iterator
clothes.forEach(items => {
items.forEach((item) => {
total++ // iterate by one each time around
})
})
return total
}
console.log('all clothes: ' + totalItems());