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

javascript - How do I get JS to print out the strings within an array whilst being in bullet points on separate lines? - Stack O

programmeradmin0浏览0评论

We were given code in puter science which we were supposed to look at and explain and then we're supposed to add to it.

This is the code:

<!DOCTYPE html>
<html>
<head>
<title>Example Website</title>
</head>
<body>
<p id="demo"></p>

<script>

var array = ["example1","example2","example3"];

document.getElementById("demo").innerHTML = array[0]

</script>

</body>
</html>

What he wanted us to do now was make it print the array in separate lines with bullet points instead of just printing the first thing within the array which is 'example1'.

He said to use any resources you can from the internet to find out how and to try and remember the information found and then explain it during class.

We were given code in puter science which we were supposed to look at and explain and then we're supposed to add to it.

This is the code:

<!DOCTYPE html>
<html>
<head>
<title>Example Website</title>
</head>
<body>
<p id="demo"></p>

<script>

var array = ["example1","example2","example3"];

document.getElementById("demo").innerHTML = array[0]

</script>

</body>
</html>

What he wanted us to do now was make it print the array in separate lines with bullet points instead of just printing the first thing within the array which is 'example1'.

He said to use any resources you can from the internet to find out how and to try and remember the information found and then explain it during class.

Share Improve this question asked Jun 7, 2016 at 18:32 BlizzardGizzardBlizzardGizzard 492 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Well, you can use .join(), <ul> and <li>s. The .join() helps in converting the array into a string joined by the parameter given in the .join().

<p id="demo"></p>
<script>
  var array = ["example1","example2","example3"];
  document.getElementById("demo").innerHTML = '<ul><li>' + array.join("</li><li>"); + '</li></ul>';
</script>

The above displays like:

A bullet point list in HTML looks like this:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

So to print something like that you'll want to follow these steps:

  1. Print out the opening <ul> tag
  2. Loop through the array and print each array element surrounded by <li> tags
  3. Print out the closing </ul> tag

var array = ['example1', 'example2', 'example3'];

var s = '<ul>';

for (var i = 0; i < array.length; i++) {
  s += '<li>' + array[i] + '</li>';
}

s += '</ul>'

document.getElementById("demo").innerHTML = s;
<div id="demo"></div>

发布评论

评论列表(0)

  1. 暂无评论