首页 > 解决方案 > 如何解决带有 TypeError 的 forEach 循环?

问题描述

它显示:

TypeError - 无法读取未定义的属性。

这里有什么问题?

calcTotal: function(type) {
    sum = 0;
    data.allItems[type].forEach(function() {
        sum += data.totals[type];
        data.totals[type] = data.totals[type] + sum;
        tbudget = data.totals.inc - data.totals.exp;
        console.log(tbudget);
    }
)
},

标签: javascriptforeachtypeerror

解决方案


你的forEach回调应该有一些参数。这是格式,根据MDN

arr.forEach(function callback(currentValue[, index[, array]]) { /*...*/ }

我不确切知道您的“数据”数组是什么样子,但至少您内部的一些引用forEach几乎肯定应该查看每个数组成员,而不是data数组本身。例如,我猜你的总和应该查看每个成员,如果每个成员都有一个totals包含各种types 的属性,则可能是这样的:

calcTotal: function(type) {
    sum = 0;
    data.allItems[type].forEach(function(item) {
        sum += item.totals[type];
        // ...
    }
)
},

推荐阅读