我有这个相当重复的代码,所以我想知道是否有人可以帮助我将其转换为JavaScript循环(如有必要,包括数组),因为我对它们的了解非常有限。 这是代码:
//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);
如果这不符合问题规定,请随意将其删除,但我只是寻求帮助。 :)
任何帮助将不胜感激,提前感谢! :d
答案 0 :(得分:3)
你可以这样做:
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);
}
}
答案 1 :(得分:1)
以这种方式:
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);
}
}
答案 2 :(得分:0)
这应该可行,但老实说它会使代码更难阅读并且可能更慢。
我宁愿按你的方式去做,但是你走了:
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);
}