2014-10-08 214 views
2

我有一个包含用户选择放入其中的项目的帐单数组。添加新元素或更新数组中的现有元素

例如, {项目:“奶”,费用:1.99,数量:1}

我想什么做的是更新量为2如果另一个牛奶被添加到篮下,而不是添加其他牛奶项目。这是什么样的代码,我目前所面对的:

for (var i = 0; i < bill.length; i++) { 
    if (newItem == bill[i].item) { 
     bill[i].quantity++; 
    } 

    //IF IT CANNOT BE FOUND ADD NEW ITEM 
    bill.push({ 
     item: newItem, 
     cost: cost, 
     quantity: 1}); 
} 
+1

当您的循环完成后,您只需知道物品是否存在。 – ajp15243 2014-10-08 15:38:51

+0

'push'会将一个项目添加到数组中。看看这个帖子http://stackoverflow.com/questions/4689856/how-to-change-value-of-object-which-is-inside-an-array-using-javascript-or-jquer – Bram 2014-10-08 15:40:04

+0

你的代码看起来不错, 问题是什么? – 2014-10-08 15:40:44

回答

2

break退出循环,并设置一个标志,如果它发现:

var found = false; 
for(var i = 0; i < bill.length; i++){ 
    if(newItem == bill[i].item){ 
     bill[i].quantity++; 
     found = true; 
     break; 
    } 
} 

if (!found) { 
    bill.push({ 
     item: newItem, 
     cost: cost, 
     quantity: 1 
    }); 
} 
+3

不起作用。你推动每一次迭代,这不匹配。 – mpen 2014-10-08 15:39:35

+0

@Mark - 正在编辑:D – tymeJV 2014-10-08 15:40:00

0

可以使用的ECMAScript 6和谐阵列方法findIndex()

function addItem(newItem, cost, quantity) { 
    var index = bill.findIndex(function(element) { 
     return element.item === newItem; 
    }); 
    if (index >= 0) { 
     bill[index].quantity += quantity; 
    } else { 
     bill.push({item: newItem, cost: cost, quantity: quantity}); 
    } 
} 

它将返回,如果没有这样的元素被发现的谓词,或者-1匹配的数组的元素的索引。例如,下列代码:

var bill = [{ item: 'Milk', cost: 1.99, quantity: 1 }]; 
addItem('Milk', 1.99, 1); 
addItem('Bread', 1.00, 1); 
console.log(bill); 

产生输出:

[{项目: '牛奶',成本:1.99,数量:2}, {项目: '面包',成本:1,数量:1}]

findIndex()方法不是很广泛支持的是,但有一个findIndex() polyfill

if (!Array.prototype.findIndex) { 
    Array.prototype.findIndex = function(predicate) { 
    if (this == null) { 
     throw new TypeError('Array.prototype.find called on null or undefined'); 
    } 
    if (typeof predicate !== 'function') { 
     throw new TypeError('predicate must be a function'); 
    } 
    var list = Object(this); 
    var length = list.length >>> 0; 
    var thisArg = arguments[1]; 
    var value; 

    for (var i = 0; i < length; i++) { 
     value = list[i]; 
     if (predicate.call(thisArg, value, i, list)) { 
     return i; 
     } 
    } 
    return -1; 
    }; 
}