好的,我已经完成了搜索和尝试无法正常工作的代码块。这就是我得到的。
我点击图片时构建数组。
invoices.addItem = function(id) {
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
我想检查一下,当再次点击图像时,ID
是否已经存在于数组中,如果它确实增加了数量。
所有我要求的是一种检查id是否存在的简单方法,如果它确实返回true,则返回false。
if(id exists)
{
return true;
}
return false;
如何让ID存在工作!?!?!?!?!?!?!?!
更新
这就是我拥有的一切:
invoices.addItem = function(id) {
if(invoices.checkItem(id))
{
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
var qty = invoices.newInvoiceItems[index].qty;
invoices.newInvoiceItems[index].qty = qty++;
}
else
{
return false;
}
}
}
else
{
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
}
invoices.removeItem = function(index) {
invoices.newInvoiceItems.splice(index, 1);
}
invoices.checkItem = function(id) {
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
return true;
}
else
{
return false;
}
}
}
我们说我有两件商品Item A
和Item B
。如果我单击项目A,它会将其添加到数组中。然后再次单击它,它不会添加它,但只增加一次数量。现在,如果我点击项目B而不刷新页面,那么每次点击项目B时,它都会反复添加。
我已经控制台记录了返回的ID,它始终是相同的,即使每个项目都有自己的ID。
答案 0 :(得分:2)
您可以使用Array.prototype.filter
快速轻松地查找数组中的项目。如果找到该项目......那么你知道它存在。
var existingItem = invoices.newInvoiceItems.filter(function(item){
return item.id === id;
})[0];
if(existingItem ){
++existingItem.qty
}else{
//do your firebase thing...
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : 1
});
});
}