2012-09-27 2 views
1

아래 코드를 가지고 있지만 if 문 안에있는 경우 items.push이 작동하지 않습니다. }을 끝내기 전에 줄의 주석을 제거하면 items.push이 예상대로 작동합니다. 내가 typeof 당신의 변수가 무엇인지 정말 모르겠습니다푸시가 if 문 내부에서 작동하지 않습니다.

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

[자바 스크립트 루프의 오류 (배열에 푸시가 작동하지 않음)] 가능한 중복] (http://stackoverflow.com/questions/12628321/error-in-javascript-loop-push-to-array-does-not-work) – Pointy

답변

0

, 그것은 number 아니면 그냥 string입니까?

typeof row.amount == "string" 또는 typeof myrowpaid.Amount == "string"이면 if 조건이 실행되지 않습니다.

확인하려면 변수는 이미 다음 items 변수를 deceleared하지 않을 경우 수

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>'); 
      } 

로 변환 parseInt() 기능을 사용

변수 항목을 사용하기 전에 var items = [];을 추가, number 유형
+1

여러 가지 문제가있을 수 있지만 실제 문제는 그가 모든 쿼리 콜백이 완료되기 전에 배열을 사용하려고한다는 것입니다. – Pointy

+0

그는 items.push가 if 조건 외부에서 작동한다는 것을 말하고 있으므로 항목 변수를 이미 배열로 선언했을 수도 있습니다. –

+0

하지만이 경고 (row.amount- myrowpaid.Amount); 두 값이 숫자 – kosbou