首页 文章

如何使用TypeError解决forEach循环?

提问于
浏览
0

它显示:

TypeError - 无法读取undefined的属性 .

这有什么问题?

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);
    }
)
},

1 回答

  • 0

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

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

    我不确切知道你的"data"数组是什么样的,但至少你的 forEach 中的一些引用几乎肯定应该是在查看每个数组成员,而不是 data 数组本身 . 例如,我猜你的总和应该看着每个成员,如果每个成员都有一个 totals 属性,包含各种 type

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

相关问题