How to Print Array elements on a Webpage
When you are working with arrays in JavaScript, you will want to print out the elements of your array.
In a browser environment, you have two options, using the console.log()
function or writing it to the DOM.
In this post, we'll see examples of the two best ways to print out your array.
Using the console.log()
function
The easiest way to print out an array is to use the console.log()
function.
You can loop through each element, printing it out one by one.
First, let's start with our array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
Then, let's loop through the array and print out each element:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
BASH1
2
3
4
5
Writing the results to the DOM
To write your array to the DOM, you will first need to convert your array to a string.
Thankfully, we can take advantage of the JSON.stringify()
function to do this.
We can have the JSON.stringify()
function convert our array to a string, and then we can write the string to the DOM.
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const string = JSON.stringify(array);
document.querySelector(".output").innerHTML = string;
BASH[1, 2, 3, 4, 5]
Here's a full example:
HTML<!DOCTYPE html>
<html>
<head>
<title>JavaScript Array example</title>
</head>
<body>
<pre class="output"></pre>
<script>
const array = [1, 2, 3, 4, 5];
const string = JSON.stringify(array, null, 4);
document.querySelector(".output").innerHTML = string;
</script>
</body>
</html>
BASH[
1,
2,
3,
4,
5
]
You've successfully printed out your array to the DOM!
Conclusion
In this post, we looked at examples of the two best ways to print out your array.
The two ways are using the console.log()
function and then writing the results directly to the DOM.
Hopefully, this post has been useful to you!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Getting Started with Electron
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js