如果语句,push不起作用

时间:2012-09-27 19:35:49

标签: javascript arrays loops

我有下面的代码,但是items.pushif语句中时不起作用。如果在结束}之前取消注释该行,则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>');

}

1 个答案:

答案 0 :(得分: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>');
            }

如果你还没有减慢items变量,那么在使用items变量之前添加var items = [];