Nachtara
Nachtara

Reputation: 35

Is there a way to condense this into fewer lines? HTML

My code that I'd like to condense:

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];

I see three main sections that look like they can be condensed. I'd also, perhaps, prefer a way to be able to add or subtract an arbitrary number of buildings without changing too much of the code.

Upvotes: 0

Views: 84

Answers (2)

Marie
Marie

Reputation: 2217

Just in case, here is another way to do it without hard coding an array of letters. Another benefit is that this avoids Array.prototype.forEach which is not available in Internet Explorer 8

var start = "A".charCodeAt(0);
var end = "H".charCodeAt(0);

for (var i = start; i <= end; i += 1) {
  var row = String.fromCharCode(i);
  document.getElementById('cost' + row).innerHTML = currentCost[i - start];
  document.getElementById('amount' + row).innerHTML = building[i - start];
  document.getElementById('bonus' + row).innerHTML = currentBonuses[i - start];
}

Upvotes: 3

Rajesh
Rajesh

Reputation: 24915

You can update in a loop. Following is a very basic representation:

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

Upvotes: 8

Related Questions