最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Simpler way to print array items into list items (JavaScript) - Stack Overflow

programmeradmin7浏览0评论

going through some exercises in a book. Had to print out array items into a list element.

This was the solution supplied by the book.

<!doctype html>
<html lang="en">

<head>
  <title>Temperatures</title>
  <meta charset="utf-8">
  <script>
    function showTemps() {
      var tempByHour = new Array();
      tempByHour[0] = 59.2;
      tempByHour[1] = 60.1;
      tempByHour[2] = 63;
      tempByHour[3] = 65;
      tempByHour[4] = 62;
      for (var i = 0; i < tempByHour.length; i++) {
        var theTemp = tempByHour[i];
        var id = "temp" + i;
        var li = document.getElementById(id);
        if (i == 0) {
          li.innerHTML = "The temperature at noon was " + theTemp;
        } else {
          li.innerHTML = "The temperature at " + [i] + " was " + theTemp;
        }
      }
    }
    window.onload = showTemps;
  </script>
</head>

<body>
  <h1>Temperatures</h1>
  <ul>
    <li id="temp0"></li>
    <li id="temp1"></li>
    <li id="temp2"></li>
    <li id="temp3"></li>
    <li id="temp4"></li>
  </ul>
</body>

</html>

going through some exercises in a book. Had to print out array items into a list element.

This was the solution supplied by the book.

<!doctype html>
<html lang="en">

<head>
  <title>Temperatures</title>
  <meta charset="utf-8">
  <script>
    function showTemps() {
      var tempByHour = new Array();
      tempByHour[0] = 59.2;
      tempByHour[1] = 60.1;
      tempByHour[2] = 63;
      tempByHour[3] = 65;
      tempByHour[4] = 62;
      for (var i = 0; i < tempByHour.length; i++) {
        var theTemp = tempByHour[i];
        var id = "temp" + i;
        var li = document.getElementById(id);
        if (i == 0) {
          li.innerHTML = "The temperature at noon was " + theTemp;
        } else {
          li.innerHTML = "The temperature at " + [i] + " was " + theTemp;
        }
      }
    }
    window.onload = showTemps;
  </script>
</head>

<body>
  <h1>Temperatures</h1>
  <ul>
    <li id="temp0"></li>
    <li id="temp1"></li>
    <li id="temp2"></li>
    <li id="temp3"></li>
    <li id="temp4"></li>
  </ul>
</body>

</html>

I tried going against the book's solution at first and tried to just use a for loop and use the create element method and have the messages print out alongside with them that way but had no luck.

var messageGen = function() {
var forecastByHour = [32, 15, 19, 25, 21];


for (var i =0; i <= forecastByHour.length; i++) {
  var temp = forecastByHour[i];
  var message = "On the " + [i] + " hour the expected forcase is to be" + temp;
  var listItems = document.createElement("li");

    listItems.innerHTML = message
}

}

Anybody have a simpler solution to this?

Share Improve this question edited Apr 23, 2017 at 4:01 user663031 asked Apr 23, 2017 at 3:32 jonathanpucjonathanpuc 1793 silver badges12 bronze badges 1
  • you've shown the code that works, mentioned an abstract code that doesn't, and expect help with code you haven't posted - good luck ... also, you use the word print - there's nothing in the code that would print anything – Jaromanda X Commented Apr 23, 2017 at 3:39
Add a ment  | 

2 Answers 2

Reset to default 5

You can use fancy Array manipulation functions like map and join to efficiently construct HTML and manipulate your temperatures. This code is much easier to follow than the posted solution once you understand the higher-level methods behind it (see the linked MDN documentation pages).

function showTemperatures() {
  var temperatures = [59.2, 60.1, 63, 65, 62].map(function (t, i) {
    return 'The temperature at ' + (i || 'noon') + ' was ' + t
  })

  document.getElementById('temperatures').innerHTML =
    '<li>' + temperatures.join('</li><li>') + '</li>'
}

showTemperatures()
<h1>Temperatures</h1>
<ul id="temperatures"></ul>

This is how I would approach this problem:

  1. Make an array of data.
  2. Create a function to produce an li based on parameters.
  3. Use a for loop to appendChild a li to your target ul element.

var tempByHour = [ 59.2, 60.1, 63, 65, 62 ];

function createLi(temp, i) {
    var li = document.createElement("LI");
    
    if (i === 0) {
        li.innerText = "The temperature at noon was " + temp;
    } else {
        li.innerText = "The temperature at " + i + "was " + temp;
    }
    
    return li;
}

var i,
    len = tempByHour.length,
    target = document.getElementById("temps");

for (i = 0; i < len; i++) {
    target.appendChild(createLi(tempByHour[i], i));
}
<h1>Temperatures</h1>
<ul id="temps"></ul>

I use for loops instead of maps or forEach loops. If you benchmark the different methods, for loops are ~60% fast than maps & ~80% faster than forEach loops.

发布评论

评论列表(0)

  1. 暂无评论