var colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"]
for (var i = 0; i<colours.length; i++){
document.write(" " + colours [i]);
}
我必须创建一个网页,该网页具有一系列存储在数组中的颜色以循环遍历每个元素。问题是,结果是所有颜色都在一行中。如何使它每次都输出新行?
答案 0 :(得分:2)
在<br>
中添加一个document.write
标记。 <br>
创建一个换行符,该换行符将打印新行中的下一个元素
var colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"]
for (var i = 0; i<colours.length; i++){
document.write(" " + colours [i] + '<br>');
}
答案 1 :(得分:1)
尝试以下操作-添加中断标签<br>
,为进一步简化,您还可以使用Array.join避免循环。
var colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"]
document.write(colours.join("<br/>"));
答案 2 :(得分:0)
您必须使用<br>
元素在HTML中创建新行。
您还可以创建一个字符串并将其写入文档一次。为此,请使用Array.map()
将颜色数组映射到颜色加上<br>
,然后使用Array.join('')
将此数组加入。
const colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"];
document.write(colours.map(c => `${c}<br>`).join(''));
或更简单地,将颜色数组与<br>
字符串连接:
const colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"];
document.write(colours.join('<br>'));
答案 3 :(得分:0)
使用换行符
var colours = ["Blue","Red","Green","Yellow","Purple","Black","Orange"]
for (var i = 0; i<colours.length; i++){
document.write("<span style='background-color:"+colours[i]+"'>" + colours [i] +"</span><br>");
}