添加对象值 Javascript

Adding Object Values Javascript

本文关键字:Javascript 对象 添加      更新时间:2023-09-26

我正在尝试使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');
}

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

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

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

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

我不是 100% 确定您在这里要完成什么,但是如果您希望将其绑定为对象属性,您可以执行这样的事情...

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
// 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());