2014-09-12 169 views
-1

我想濃縮我的代碼,因爲我有很多重複編碼發生。我將需要多次應用此相同的示例。我想創建一個for循環,但我的變量也需要增加。現在我有我的變量增加,但我無法實現我的細胞數據到變量。我想我是雙重分配變種h。我無法弄清楚如何解決這個問題。感謝您的幫助。申請循環變量

For循環

for (var j = 2; j<15; j++){eval("var polebrea" +j); 
var h = ("polebrea" +j) 
} 

h = document.getElementById("part1Table").rows[10].cells[2].innerHTML; 

代碼試圖實施

polebrea2 = document.getElementById("part1Table").rows[10].cells[2].innerHTML; 
polebrea3 = document.getElementById("part1Table").rows[10].cells[3].innerHTML; 
polebrea4 = document.getElementById("part1Table").rows[10].cells[4].innerHTML; 
polebrea5 = document.getElementById("part1Table").rows[10].cells[5].innerHTML; 

(續15)

插入可變

<script>document.write(polebrea2)</script> 
+0

不要使用'eval'。創建一個可以索引的數組。 – 2014-09-12 16:32:09

+0

使用一個對象來存儲它們,而不是爲每個對象創建一個新變量。 'object [「polebrea」+ j]' – GillesC 2014-09-12 16:32:13

+3

動態命名變量是某處設計不好的標誌。使用可以容納某些東西的數據結構,如對象或數組。 – 2014-09-12 16:33:17

回答

0

忽略設計教條....使用的屬性訪問字符串形式的索引來設置變量:

// window is a bad place for this....you should probably put it on another object e.g. var polbreas = {}; 
for (var i = 2; i<15; i++){ 
    window["polbrea"+i] = document.getElementById("part1Table").rows[10].cells[i].innerHTML; 
} 
+0

謝謝約書亞,你的回答是正確的,我正在尋找,它的工作原理沒有改變任何東西。我幾次親自接近這個,但不知道我哪裏出錯了。現在我所要做的就是使用(document.write(polbrea2)),它給了我正確的單元格。我有其他的if語句會拉動其他數字。 – 2014-09-13 14:55:09

-2

雖然不一定好做法,你在做什麼,你可以試試這個:

var createVariable = function(index){ 
    var variableName = "polebrea" + index; 
    var objName = document.getElementById("part1Table").rows[10].cells[index].innerHTML; 
    return (variableName + " = " + objName + ";"); 
}; 

for (var j = 2; j<15; j++){ 
     var objToWrite = createVariable(j); 
     console.log(objToWrite); 
} 
+0

小心評論爲什麼downvote? – ochi 2014-09-15 21:31:24