簡體   English   中英

如果ID存在於使用angularjs的javascript數組中

[英]If ID exists in javascript array with angularjs

好的,我已經完成搜索並嘗試了無效的代碼塊。 這就是我得到的。

當我單擊圖像時,我正在構建一個數組。

    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 AItem B 如果我單擊項目A,它將添加到數組中。 然后再次單擊它,它不會添加,只會增加數量一次。 現在,如果我在不刷新頁面的情況下單擊項目B,則每次單擊項目B時,它都會一遍又一遍地添加它。

我已經在控制台記錄了返回的ID,即使每個項目都有其自己的ID,它也始終是相同的。

您可以使用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
        });
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM