我想简化的代码:
document.getElementById("costA").innerHTML = currentCost[0];
document.getElementById("costB").innerHTML = currentCost[1];
document.getElementById("costC").innerHTML = currentCost[2];
document.getElementById("costD").innerHTML = currentCost[3];
document.getElementById("costE").innerHTML = currentCost[4];
document.getElementById("costF").innerHTML = currentCost[5];
document.getElementById("costG").innerHTML = currentCost[6];
document.getElementById("costH").innerHTML = currentCost[7];
document.getElementById("amountA").innerHTML = building[0];
document.getElementById("amountB").innerHTML = building[1];
document.getElementById("amountC").innerHTML = building[2];
document.getElementById("amountD").innerHTML = building[3];
document.getElementById("amountE").innerHTML = building[4];
document.getElementById("amountF").innerHTML = building[5];
document.getElementById("amountG").innerHTML = building[6];
document.getElementById("amountH").innerHTML = building[7];
document.getElementById("bonusA").innerHTML = currentBonuses[0];
document.getElementById("bonusB").innerHTML = currentBonuses[1];
document.getElementById("bonusC").innerHTML = currentBonuses[2];
document.getElementById("bonusD").innerHTML = currentBonuses[3];
document.getElementById("bonusE").innerHTML = currentBonuses[4];
document.getElementById("bonusF").innerHTML = currentBonuses[5];
document.getElementById("bonusG").innerHTML = currentBonuses[6];
document.getElementById("bonusH").innerHTML = currentBonuses[7];
我看到三个主要部分看起来可以浓缩。或许,我也许更愿意在不改变太多代码的情况下添加或减少任意数量的建筑物。
答案 0 :(得分:8)
您可以循环更新。以下是一个非常基本的表示:
var alphabetArr = ["A", "B","C","D","E","F","G","H"];
alphabetArr.forEach(function(row, i){
document.getElementById("cost" + row).innerHTML = currentCost[i];
document.getElementById("amount" + row).innerHTML = building[i];
document.getElementById("bonus" + row).innerHTML = currentBonuses[i];
})
答案 1 :(得分:3)
以防万一,这是另一种方法,无需硬编码字母数组。另一个好处是,这可以避免Internet Explorer 8中无法使用的SearchAbout beq_nat.
Array.prototype.forEach