简体   繁体   中英

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. Basically, I am trying to print this to a webpage (not the console):

12 grape

98 kiwi

0 banana

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:

 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:

<div id="container"></div>

Example: https://jsfiddle.net/diogocosta/u8w7s49v/2/

Cheers,

That's because document.getElementById(fruits[i].id) is looking for HTML elements that don't exist.

You need to create two more p elements and assign them ids 0 , 1 , and 2 . Like this:

<p id=“0”></p>
<p id=”1”></p>
<p id=“2”></p>

before your <script> tag.

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. You can't concatenate a Number to a String directly by using the + operator in 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

BR,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM