0
我有自定义对象的数组,我想迭代缩短循环,但这不起作用,每次它返回“0”。
for(var i =0;i<array.length;i++)
的作品就像一个魅力对于in和for each循环不适用于对象数组
这里是我的类
var Product = (function() {
var nextId = 0;
return function Product(name, quantity, price, picture) {
this.id = nextId++;
this.name = name;
this.quantityInStock = quantity;
this.price = price;
this.picture = picture;
}
})();
var Cart = (function() {
var nextId = 0;
return function Cart(productList) {
this.id = nextId++;
this.productList = (productList === undefined || !productList instanceof Array) ? [] : productList;
}
})();
Cart.prototype.addProduct = function (product) {
(product instanceof Product) ? this.productList.push(product) : console.log("Invalid object type");
};
Cart.prototype.calculateLumpSum = function() {
var sum = 0;
this.productList.forEach(function (product) { // doesn't work as well as for in loop
sum += product.price;
});
return sum;
};
请帮哪里是我的错,再简单的for循环运作良好
编辑
无论在也不forEach循环与该数组一起工作,在调试器中它显示例如
for(var product in productList) {
}
产品在这种情况下等于"0"
,但数组是正确的,并添加了项目。
尝试创建一个运行在jsbin或类似环境中的测试用例。目前还不清楚你在问什么,在你的例子中有很多不相关的代码。 –
在这种情况下,您可以使用'.reduce'来代替'.forEach'来获得总和。 –
请参阅我的编辑 – fheoosghalzr