简体   繁体   中英

Can anyone help me make a for loop for this code?

I have this code which is rather repetitive, so I was wondering whether someone could help me convert it into a loop in JavaScript (including an array if necessary), as my knowledge of them is very limited. Here is the code:

//9 Carat Gold
document.getElementById("9CGGBP").innerHTML = (data[0] * data[4]).toFixed(2);
document.getElementById("9CGUSD").innerHTML = (data[0] * data[5]).toFixed(2);
document.getElementById("9CGEUR").innerHTML = (data[0] * data[6]).toFixed(2);

//18 Carat Gold
document.getElementById("18CGGBP").innerHTML = (data[1] * data[4]).toFixed(2);
document.getElementById("18CGUSD").innerHTML = (data[1] * data[5]).toFixed(2);
document.getElementById("18CGEUR").innerHTML = (data[1] * data[6]).toFixed(2);


//Silver
document.getElementById("SGBP").innerHTML = (data[2] * data[4]).toFixed(2);
document.getElementById("SUSD").innerHTML = (data[2] * data[5]).toFixed(2);
document.getElementById("SEUR").innerHTML = (data[2] * data[6]).toFixed(2);

//Platinum
document.getElementById("PGBP").innerHTML = (data[3] * data[4]).toFixed(2);
document.getElementById("PUSD").innerHTML = (data[3] * data[5]).toFixed(2);
document.getElementById("PEUR").innerHTML = (data[3] * data[6]).toFixed(2);

If this does not comply with the question regulations, feel free to remove it, but I am just seeking help. :)

Any help will be greatly appreciated, thanks in advance! :D

You could do something like this:

var types = ["9CG", "18CG", "S", "P"];
var currencies = ["GBP", "USD", "EUR"];

for (var i = 0; i < types.length; i++) {
  for (var j = 0; j < currencies.length; j++) {
    document.getElementById(types[i] + currencies[j]).innerHTML = (data[i] * data[4 + j]).toFixed(2);
  }
}

Here's one way:

var prefixes = ["9CG", "18CG", "S", "P"],
    currencies = ["GBP", "USD", "EUR"],
    prefix, baseData, i, j;

for (i = 0; i < prefix.length; ++i) {
    prefix = prefixes[i];
    baseData = data[i];
    for (j = 0; j < currencies.length; ++j) {
        document.getElementById(prefix + currencies[j]).innerHTML =
            (baseData * data[4 + j]).toFixed(2);
    }
}

This should work, though honestly it makes the code harder to read and probably slower.

I would rather do it the way you have it, but here you go:

var idArray = ["9CGGBP","9CGUSD","9CGEUR","18CGGBP","18CGUSD","18CGEUR","SGBP","SUSD","SEUR","PGBP","PUSD","PEUR"];
for (var i=0; i<12; i++) {
    document.getElementById(idArray[i]).innerHTML = (data[Math.floor(i/3)] * data[i%3+4]).toFixed(2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM