[英]For in and forEach loop doesn't work on array of objects
我有一组自定义对象,我想用Shortcut循环进行迭代,但这在每次返回“ 0”时均不起作用。
for(var i =0;i<array.length;i++)
就像一个符咒
这是我的课
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 in和forEach循环都不适用于此数组,例如在调试器中,它表明
for(var product in productList) {
}
在这种情况下,乘积等于"0"
但数组正确且已添加项目。
我假设这段代码:
Cart.prototype.calculateLumpSum = function () {
var sum = 0;
for(var product in this.productList) {
sum += product.price;
}
return sum;
};
如果product.price
存在并且具有价值,那么这将完美地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.