对于in和forEach循环不适用于对象数组

时间:2015-11-05 23:02:38

标签: javascript arrays performance loops

我有自定义对象数组,我想用缩短循环进行迭代,但每次返回“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;
};

请帮助我的错在哪里,再简单的循环工作

编辑

in和for循环都不适用于此数组,在调试器中它显示了例如

for(var product in productList) {

}
在这种情况下,

产品等于"0",但数组是正确的,并添加了项目。

1 个答案:

答案 0 :(得分:0)

我假设这段代码:

Cart.prototype.calculateLumpSum = function () {
    var sum = 0;
    for(var product in this.productList) {
        sum += product.price;
    }
    return sum;
};

如果product.price存在并具有价值,则此功能完美无缺。