添加对象值Javascript

时间:2013-11-12 00:16:26

标签: javascript

我正在努力使Javascript自动汇总库存中商品的价格,并显示库存中的商品总数。我必须这样做,以便它适用于任何添加到库存的金额。这就是我到目前为止所拥有的。感谢

function inventory (a,b,c)
{
this.name = a;
this.price = b;
this.id = c;


var item1 = new item ("Pen", 2.50,"001");
var item2 = new item ('Pencil', 1.25, '002');
var item3 = new item ('Paper', 0.75, '003');
}

3 个答案:

答案 0 :(得分:1)

我建议使用像Underscore或Lodash这样的库。它们提供了许多用于操作数组,集合和对象的实用程序函数。

具体来说,请查看reduce()函数:http://underscorejs.org/#reduce

因此,如果您有一系列商品,要获得价格总和,您需要做的就是:

var sum = _.reduce(items, function(total, item){return total + item.price;}, 0);

答案 1 :(得分:0)

// By convention, class names should begin with an uppercase letter
function Item (a,b,c) {
    this.name = a;
    this.price = b;
    this.id = c;
}

function getTotal() {
    var total = 0;
    // Loop over the inventory array and tally up the total cost
    for (var i = 0; i < inventory.length; i ++) {
        total += inventory[i].price;
    }
    return total;
}

// We can store our item instances on an array
var inventory = [
    new Item ("Pen", 2.50,"001"),
    new Item ('Pencil', 1.25, '002'),
    new Item ('Paper', 0.75, '003')
];

console.log('Total is:', getTotal());

答案 2 :(得分:0)

我不是百分之百确定你要在这里完成什么,但如果你想把它绑定为一个对象属性,你可以做这样的事情......

var Inventory = {
    "items" : [
        { "name" : "paperclip", "price" : 25 },
        { "name" : "folder", "price" : 350 },
        { "name" : "desk", "price" : 2999 }
    ],
    "total" : function totalItems() {
        var total = 0;
        this.items.forEach(function(item) {
            total += item.price;
        });
        return total;
    }
};

console.log( Inventory.total() ); // 3275
console.log( Inventory.items.length ) // 3, # items