javascript - 如何解决带有 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);
}
)
},
解决方案
你的forEach
回调应该有一些参数。这是格式,根据MDN
arr.forEach(function callback(currentValue[, index[, array]]) { /*...*/ }
我不确切知道您的“数据”数组是什么样子,但至少您内部的一些引用forEach
几乎肯定应该查看每个数组成员,而不是data
数组本身。例如,我猜你的总和应该查看每个成员,如果每个成员都有一个totals
包含各种type
s 的属性,则可能是这样的:
calcTotal: function(type) {
sum = 0;
data.allItems[type].forEach(function(item) {
sum += item.totals[type];
// ...
}
)
},
推荐阅读
- javascript - 如何根据比较值映射两个数组
- spartacus-storefront - 模块中定义的 PDP 自定义路由不起作用
- python-3.x - 如何修剪左右两侧的网址?
- android-testing - Flutter 驱动程序如何与 Android 配合使用?
- python - 使用 NA 和 data.table 将 R 数据导入 Python 问题
- angular - 表单生成器“无法读取 null 的属性 (...)”
- html - 如何处理导致移动设备上图像模糊的 CSS sprite(使用背景位置)问题?
- css - 从外部角度项目访问样式
- r - 在 R 中包括检测限和/或不等式元数据
- javascript - 在 React.js 正则表达式函数中使用字符串插值