2014-01-29 70 views
2

定義他們,我有以下代碼(阿賈克斯):變量不爲零時,我使用「變種」

for(i in data.collection1) { 
    var var1, var2, var3, var4 = 0; 
    for (j in data.collection1[i].collection2) { // might be empty 
    var current = data.collection1[i].collection2[j]; 
    if (current != 'undefined') { 
     if (current.status == 'status1') var1 = current.count; 
     if (current.status == 'status2') var2 = current.count; 
     if (current.status == 'status3') var3 = current.count; 
     if (current.status == 'status4') var4 = current.count; 
    } 
    } 

    var str = $(["<tr>", "<td>", data.collection1[i].obj1.name, "</td>", 
    "<td>", var1, "</td>", 
    "<td>", var2, "</td>", 
    "<td>", var3, "</td>", 
    "<td>", var4, "</td>", "</tr>"].join("")); 

    $("#tbl1 tr:last").after(str); 
} 

奇怪的是,當data.collection1[i].collection2是在一些迭代空中,變量var1, var2, var3, var4不等於zero,而是保持其先前的值(來自先前的迭代)。

這是爲什麼,我該如何擺脫它?

P.S.順便說一句,他們有什麼方法來簡化這個代碼?

回答

10
var var1, var2, var3, var4 = 0; 

表態意味着

聲明在局部範圍var1, var2, var3, var4變量,var4值還設置爲0

如果您想爲其他變量的值把= 0爲每個變量:

var var1 = 0, 
    var2 = 0, 
    var3 = 0, 
    var4 = 0; 
+2

或者,'var var1,var2,var3,var4;'和'var1 = var2 = var3 = var4 = 0' – David

相關問題