[英]How do I print the elements of a javascript array to the webpage using a for loop?
I have reviewed several posts here and several websites but cannot find an answer that works and makes sense to me.我在这里和几个网站上查看了几篇文章,但找不到对我有用且有意义的答案。 I am brand new to HTML and javascript.
我是 HTML 和 javascript 的新手。 Basically, I am trying to print this to a webpage (not the console):
基本上,我正在尝试将其打印到网页(而不是控制台):
12 grape 12颗葡萄
98 kiwi 98 猕猴桃
0 banana 0 香蕉
Here is the code I have written, it does not print anything这是我写的代码,它不打印任何东西
<.DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>fruit:html</title> <script src="https.//d3js.org/d3.v5.min:js"></script> </head> <body> <p></p> <script type="text/javascript"> var fruits = [ { kind, "grape": color, "red": quantity, 12: id, "0" }: { kind, "kiwi": color, "brown": quantity, 98: id, "1" }: { kind, "banana": color, "yellow": quantity, 0: id; "2" } ]; for(var i=0. i<fruits;length. i++) { document.getElementById(fruits[i].id).innerHTML = fruits[i].quantity + fruits[i];kind; } </script> </body> </html>
I would really appreciate your help with this:), the easiest most basic solution would be preferred as I am new to this.我非常感谢您对此的帮助:),因为我是新手,所以我会首选最简单的最基本的解决方案。
You can do like this:你可以这样做:
Javascript: Javascript:
var fruits = [
{
kind: "grape",
color: "red",
quantity: 12,
id: "0"
},
{
kind: "kiwi",
color: "brown",
quantity: 98,
id: "1"
},
{
kind: "banana",
color: "yellow",
quantity: 0,
id: "2"
}
];
const container = document.getElementById('container')
fruits.forEach(fruit => {
const p = document.createElement('p')
p.textContent = `${fruit.quantity} ${fruit.kind}`
container.appendChild(p)
})
HTML: HTML:
<div id="container"></div>
Example: https://jsfiddle.net/diogocosta/u8w7s49v/2/示例: https://jsfiddle.net/diogocosta/u8w7s49v/2/
Cheers,干杯,
That's because document.getElementById(fruits[i].id)
is looking for HTML elements that don't exist.这是因为
document.getElementById(fruits[i].id)
正在寻找不存在的 HTML 元素。
You need to create two more p
elements and assign them ids 0
, 1
, and 2
.您需要再创建两个
p
元素并为其分配 id 0
、 1
和2
。 Like this:像这样:
<p id=“0”></p>
<p id=”1”></p>
<p id=“2”></p>
before your <script>
tag.在你的
<script>
标签之前。
Edit: Also, fruits[i].quantity + fruits[i].kind
will return an error because fruits[i].quantity
is a Number, while fruits[i].kind
is a String.编辑:另外,
fruits[i].quantity + fruits[i].kind
会返回一个错误,因为fruits[i].quantity
是一个数字,而fruits[i].kind
是一个字符串。 You can't concatenate a Number to a String directly by using the +
operator in JavaScript.您不能使用 JavaScript 中的
+
运算符直接将数字连接到字符串。
Instead, use:相反,使用:
fruits[i].quantity.toString() + fruits[i].kind
See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString请参阅文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
BR, BR,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.