3

Here is my code.

var products = ["Echo Dot", "Echo Plus", "Echo Auto", "Echo Show", "Echo Link"];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
toDisplay = "";
total = 0;

for (var i = 0; i < products.length; i++) {
  toDisplay += "<li>" + products[i] + " - " + prices[i] + "</li>";
  total += prices[i];
}

document.getElementById('prices').innerHTML = toDisplay;
<ol id="prices">
</ol>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73

2 Answers2

2

Use a <table> element. <table> elements have a method called insertRow which adds a new row to the table, and the row elements <tr> have a method called insertCell which adds a new cell to the row element. We'll use both of those to add the data to the table instead of accumulating an html string, like so:

var products = ["Echo Dot", "Echo Plus", "Echo Auto", "Echo Show", "Echo Link"];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
var discountPercent = 20;

var table = document.getElementById("the-table");

for (var i = 0; i < products.length; i++) {
  var row = table.insertRow();
  
  row.insertCell().textContent = products[i];
  row.insertCell().textContent = prices[i];
  row.insertCell().textContent = ((100 - discountPercent) * prices[i] / 100).toFixed(2);
}
table {
  border-collapse: collapse;
}

table td, table th {
  border: 1px solid black;
  padding: 5px 10px;
}
<table id="the-table">
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th>Price After 20% Discount</th>
    </tr>
  </thead>
</table>

I used textContent to set the text of the newly added cell instead of innerHTML that can some problems.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

Try this code :

<body>
    <table id="prices"></table>

    <script>
      var title = ["Product", "Price", "Discount"];

      var products = [
        "Echo Dot",
        "Echo Plus",
        "Echo Auto",
        "Echo Show",
        "Echo Link",
      ];

      var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];

      var discount = prices.map(myFunction);

      function myFunction(value) {
        return ((value * 80) / 100).toFixed(2);
      }

      var toDisplay = "";
      var t = "";
      var i = 0;

      for (; i < products.length; i++) {
        if (i < title.length) {
          t += "<th>" + title[i] + "</th>";
        }
        toDisplay +=
          "<tr>" +
          "<td>" +
          products[i] +
          "</td>" +
          "<td>" +
          prices[i] +
          "</td>" +
          "<td>" +
          discount[i] +
          "</td>" +
          "</tr>";
      }

      t = "<tr>" + t + "</tr>" + toDisplay;

      document.getElementById("prices").innerHTML = t;
    </script>
  </body>
Amirhossein
  • 1,148
  • 3
  • 15
  • 34