我使用以下代码将变量文本输入字段,但想知道我是否可以使用数组代替:
document.getElementById("PLG").innerHTML = PLGame;
document.getElementById("PLV").innerHTML = PLV;
document.getElementById("PLKOT").innerHTML = PLKOT;
document.getElementById("PLS1").innerHTML = PLS1;
document.getElementById("PLS2").innerHTML = PLS2;
document.getElementById("PLS3").innerHTML = PLS3;
document.getElementById("PLPred").innerHTML = PLPred;
我想应该是这样的:
for (i=0; i<myArray.length; i++)
let myArray = ["PLG","PLV","PLKOT","PLS1","PLS2","PLS3","PLPred"];
let outArray = ["PLGame","PLV","PLKOT","PLS1","PLS2","PLS3","PLPred"];
document.getElementById("myArray[i]").innerHTML = OutArray[i];
我想这有很多错误,但我还在学习JS,所以对我很宽容:)
肯定有多种方法可以做到这一点。按照您当前的逻辑,您可以创建一个for
循环,它将提供索引到两个数组并执行赋值所需的索引。
我认为稍微好一点的实现是创建一个包含对象的单一数组。这样,您就不必担心两个数组在完全相同的索引处是否具有正确的id/value对。
// method 1
const ids = ["PLG", "PLV", "PLKOT"]
const values = ["v1", "v2", "v3"]
for (let i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).innerHTML = values[i]
}
// method 2
const pairs = [
{
id: 'PLG',
value: 'v1'
},
{
id: 'PLV',
value: 'v2'
},
{
id: 'PLKOT',
value: 'v3'
}
]
pairs.forEach((pair) => {
document.getElementById(pair.id).innerHTML = pair.value
})
<h1>Method 1</h1>
<div id="PLG"></div>
<div id="PLV"></div>
<div id="PLKOT"></div>
欢迎来到javascript, Steve!
可以使用for循环来实现:
// Let's begin by comma-separating the two "let" statements into one.
let myArray = ["PLG","PLV","PLKOT","PLS1","PLS2","PLS3","PLPred"],
outArray = ["PLGame","PLV","PLKOT","PLS1","PLS2","PLS3","PLPred"];
// Then we'll use myArray inside a for loop, to call values from outArray.
for (let i = 0; i < myArray.length; i++) {
document.getElementById(myArray[i]).innerHTML = outArray[i];
}
新玩家注意-注意代码第3行区分大小写。(outArray vs outArray)
编码快乐!
去掉getElementById()的引号。当你使用引号时,它将其作为字符串而不是变量。
document.getElementById(myArray[i]).innerHTML = OutArray[i];