【发布时间】:2021-05-19 18:06:03
【问题描述】:
我正在尝试在链接到 HTML 的独立 .js 文件中的 for 循环中添加换行符。
我将变量设置为一个包含 3 个对象的数组。我希望我的 for 循环运行一次,然后使用 document.write 在浏览器的新行上打印值。但是,当我运行循环时,所有 3 个对象都显示在 1 行中,而不是实际列表中。我尝试使用 <br> 和 \n 添加换行符,但是当我这样做时,浏览器中的文本消失了。我在这里做错了什么?
let pokemonList = [{
name: 'caterpie ',
height: 0.3,
types: ['bug', 'electric']
},
{
name: 'sandslash ',
height: 1,
type: ['ground']
},
{
name: 'meowth ',
height: 0.4,
type: ['normal']
},
]
for (let i = 0; i < pokemonList.length; i++) {
document.write(pokemonList[i].name + 'height: ' + pokemonList[i].height);
}
【问题讨论】:
-
我在想
document指的是一个 html 文档。 -
<br>应该可以工作。你的代码是什么? -
也许这就是问题所在,我没有把 br 放在正确的位置。我尝试在多个位置添加它,但都没有成功。
-
我不相信
document.write被推荐了。相反,创建一个元素(例如:document.createElement('div'))并将其添加到某个父容器中。 Is document.write actually deprecated? -
非常感谢大家的快速帮助和建议!我真的很感激你们!
标签: javascript arrays for-loop line-breaks