简体   繁体   English

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

[英]For in and forEach loop doesn't work on array of objects

I have array of custom objects, I want to iterate with shorten loop, but this doesn't work, each time it returns "0". 我有一组自定义对象,我想用Shortcut循环进行迭代,但这在每次返回“ 0”时均不起作用。
for(var i =0;i<array.length;i++) works like a charm for(var i =0;i<array.length;i++)就像一个符咒

Here is my class 这是我的课

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

Please help where is my fault, again simple for loop works well 请帮助我的错在哪里,再简单的循环效果很好

EDIT 编辑

Neither for in nor forEach loop works with this array, in debugger it shows that for example for in和forEach循环都不适用于此数组,例如在调试器中,它表明

for(var product in productList) {

}

product in this case equals to "0" but array is correct and has added items. 在这种情况下,乘积等于"0"但数组正确且已添加项目。

I assume this piece of code: 我假设这段代码:

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

This works perfectly, if product.price exists and has value. 如果product.price存在并且具有价值,那么这将完美地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM