可以使用的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;
};
}
当您的循环完成后,您只需知道物品是否存在。 – ajp15243 2014-10-08 15:38:51
'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
你的代码看起来不错, 问题是什么? – 2014-10-08 15:40:44