添加对象值 Javascript
Adding Object Values 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');
}
我建议使用像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());
相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值