2012-09-27 96 views
1

我有下面的代碼,但items.push不在if語句中工作。如果在結束}之前取消註釋該行,則items.push按預期工作。推送不起作用,如果語句

for (i = 0; i < len; i += 1) { 
    row = resultexpense.rows.item(i); 

    t.executeSql('SELECT * FROM expensepayments WHERE Barcode = ?', 
    [row.barcode], 
     function(t, resultpaid) { 
      var myrowpaid, 
       myrowpaidlen; 
      myrowpaidlen = resultpaid.rows.length; 
      alert(myrowpaidlen); //alerts 1 
      if (myrowpaidlen > 0){ 
       myrowpaid = resultpaid.rows.item(0); 
       alert(row.amount); //alerts 90 
       alert(myrowpaid.Amount); //alerts 50 
       if (row.amount > myrowpaid.Amount){ 
        alert(row.amount- myrowpaid.Amount); //alerts 40 
        items.push('<li><a href="#displayexpense" data-description="' + row.description + '" data-buildingcode = "' + row.buildingcode + '" data-barcode="' + row.barcode + '" data-amount="' + row.amount + '" data-buildingaddress="' + row.buildingaddress + '">' + row.description + '</a></li>'); 
       } 
      } else { 
       items.push('<li><a href="#displayexpense" data-description="' + row.description + '" data-buildingcode = "' + row.buildingcode + '" data-barcode="' + row.barcode + '" data-amount="' + row.amount + '" data-buildingaddress="' + row.buildingaddress + '">' + row.description + '</a></li>'); 
      } 

     }); 
// items.push('<li><a href="#displayexpense" data-description="' + row.description + '" data-buildingcode = "' + row.buildingcode + '" data-barcode="' + row.barcode + '" data-amount="' + row.amount + '" data-buildingaddress="' + row.buildingaddress + '">' + row.description + '</a></li>'); 

} 
+3

'executeSql()'調用是**異步**。回調中的代碼在數據庫響應之後纔會運行,在整個循環結束後將會*。 – Pointy

+1

另外,你可能應該編輯你之前的問題,因爲它是一樣的。 – Pointy

+1

可能重複的[錯誤在JavaScript循環(推到數組不工作)](http://stackoverflow.com/questions/12628321/error-in-javascript-loop-push-to-array-does-not-work ) – Pointy

回答

0

我真的不知道typeof您的變量是什麼,是不是number或只是一個string

如果typeof row.amount == "string"typeof myrowpaid.Amount == "string"那麼if條件不會執行。

可以肯定,你的變量是number類型,使用parseInt()功能轉換成數字

if (parseInt(row.amount, 10) > parseInt(myrowpaid.Amount, 10)){ 
       alert(row.amount- myrowpaid.Amount); //alerts 40 
       items.push('<li><a href="#displayexpense" data-description="' + row.description + '" data-buildingcode = "' + row.buildingcode + '" data-barcode="' + row.barcode + '" data-amount="' + row.amount + '" data-buildingaddress="' + row.buildingaddress + '">' + row.description + '</a></li>'); 
      } 

,如果你不是已經deceleared的items變量,然後,使用的物品可變

的前添加 var items = [];
+1

可能有各種問題,但真正的問題是,他試圖在所有查詢回調完成之前使用數組。 – Pointy

+0

他說items.push在if條件之外工作,所以我認爲他可能已經將items變量聲明爲一個數組。 –

+0

但是這個警報(row.amount- myrowpaid.Amount);警告正確的結果(40),所以這兩個數字是數字 – kosbou