JavaScript Arrays can hold several pieces of data in one string. This is how we set a JavaScript Array.

#AbsoluteBeginner

JavaScript Array Syntax

var zoo = ["Tom","Dick","Harry"];
The above data values are stored in a variable. They are separated by commas and quotes.

Showing Results From A JavaScript Array

The process of showing the results from an array starts with setting an id in an element. Set a variable to store your array then use innerHTML to target the id and how the results.
<p id="foo"></p>
<script>
var zoo = ["Tom","Dick","Harry"];
var x = document.getElementById('foo');
x.innerHTML=zoo;
</script>

Another Way to Write Arrays

You can put each piece of data form an array on separate lines. Make sure you do not use a comma on the last one.
var zoo = [
"Tom",
"Dick",
"Harry",
"Joe"
];

Getting One Piece of Data Out Of A JavaScript Array

You may need to grab one piece of data out of a JavaScript array. Remember that in JavaScript the first number is 0. So if you want to get the first item you would use square brackets with the number 0 in it. [0]

Example of Getting First Item In Array

<p id="foo"></p>
<script>
var zoo = [
"Tom",
"Dick",
"Harry",
"Joe"
];
var x = document.getElementById('foo');

x.innerHTML=zoo[0];
</script>
 

Get The Third Array Item

<p id="foo"></p>
<script>
var zoo = [
"Tom",
"Dick",
"Harry",
"Joe"
];
var x = document.getElementById('foo');

x.innerHTML=zoo[2];
</script>
  Lesson 17  


Sign Up To Comment