2012-08-29 45 views
1

我試圖通過發票清單,他們的個別LineItem值, 循環,並最終有一個Ojbect [對象數組]與發票號和每個發票的所有行項目的總值。JSON:循環發票項目:添加如果發票沒有退出,更新值,如果它包含示例

var objInvoiceLineItem = function (strInvoiceNo,strValue) { 
    this.InvoiceNo= strInvoiceNo; 
    this.Value = strValue; 
} 

//

var objAllInvoices = []; 

//

function AddValueTo_objAllInvoices(myInvoice){ 
    //don't know how to look and see if the Invoice exists? 
    //jQuery.inArray? 
    //for (var i = 0; i < objAllInvoices.length - 1; i++)? 

    if exists (myInvoice.InvoiceNo) = false{ 
    var newObjInvoiceItem= 
      new objInvoiceLineItem(myInvoice.InvoiceNo, myInvoice.Value); 
     objAllInvoices.push(newObjInvoiceItem) 
    } 
    else{ 
      //need help here please 
     var obj = getobject; 
     objAllInvoices.obj.Value += myInvoice.Value; 
    } 
} 

//

var Invoice1A = new objInvoiceLineItem("Invoice1",20); 
var Invoice1B = new objInvoiceLineItem("Invoice1",50); 
var Invoice2A = new objInvoiceLineItem("Invoice2",30); 


AddValueTo_objAllInvoices(Invoice1A); 
AddValueTo_objAllInvoices(Invoice1B); 
AddValueTo_objAllInvoices(Invoice2A); 
+0

需要問一個具體的問題,讓人們知道如何提供幫助。 – kinakuta

+0

道歉,我需要一些幫助來檢查項目是否已經在ObjAllInvoices []中存在,我想我可以在獲得對象的存在幫助時更新Invoice.Value。謝謝 –

+0

發票始終保證是唯一的嗎? – kinakuta

回答

2

我覺得這樣的事情會做你想要什麼:

function AddValueTo_objAllInvoices(myInvoice) 
{ 
    for (var i = 0; i < objAllInvoices.length; i++) 
    { 
     if (objAllInvoices[i].InvoiceNo == myInvoice.InvoiceNo) 
     { 
      // invoice exists, update it and return 
      objAllInvoices[i].Value += myInvoice.Value; 
      return; 
     } 
    } 

    // if the invoice already existed, we would have returned in the loop 
    // so we wouldn't have ever gotten here, so the invoice must not exist. 
    // create it now: 
    var newObjInvoiceItem = new objInvoiceLineItem(myInvoice.Container, myInvoice.Value); 
    objAllInvoices.push(newObjInvoiceItem); 
} 
+0

輝煌!非常感謝!! –