我有一个迭代2d数组的函数,每个数组都有一个歌曲和一个解释器,该函数应该运行一个循环并用它的解释器列出每首歌曲。问题是它只列出了最后一首歌和翻译,我错过了什么,所以它列出了所有这些?:
HTML:
<ul id="2d"> </ul>
JS
var twoDArray = [
["I did it my way", "Frank Sinatra"],
["Respect", "Areta Franklin"],
["Imagine", "John Lennon"]
];
function iterative( songs ) {
for ( var i = 0; i < songs.length; i += 1) {
document.getElementById("2d").innerHTML = "<li>" + songs[i][0] + " by " + songs[i][1] + "</li>";
}
}
iterative(twoDArray);
答案 0 :(得分:4)
那是因为你每次循环都要设置innerHtml,所以除了最后一次之外每次都会覆盖它。你想这样做
document.getElementById("2d").innerHTML += "<li>" + songs[i][0] + " by " + songs[i][1] + "</li>";
答案 1 :(得分:0)
这是一种方式。希望这会有所帮助。
const twoDArray = [
["I did it my way", "Frank Sinatra"],
["Respect", "Areta Franklin"],
["Imagine", "John Lennon"]
];
const ul = document.querySelector('ul');
twoDArray.forEach(pair => {
const li = `<li>${pair[0]} by ${pair[1]}</li>`;
ul.insertAdjacentHTML('beforeend', li);
})
HTML:
<ul id="2d"> </ul>