CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Javascript Arrays

Arrays are used to store multiple values in one variable.

Here is an example:

var monsters = [ "Orc", "Ogre", "Giant" ];

Of course, you could create separate variables for them like this:

var orc; var ogre; var giant;

But, then you can't use loops to loop over all of them.

This is how you access the array:

var monsters = [ "Orc", "Ogre", "Giant" ]; print( my_monster[0] );

Try the above code and see if you can guess which monster appears.

Change 0 to 1 and notice what happens. Change it to 2.
DO IT
Did it work? Try to figure it out. If it still doesn't work just click DO IT and we'll fix the code for you.

Let's check the length of the array:

var monsters = [ "Orc", "Ogre", "Giant" ]; print( monsters.length );

What is the length of the array?

The array length will always be 1 greater than the highest element.

Add the following before the print statement

monsters[20] = "Orc";
DO IT

What's the length of the array now?

Now, we're going to loop through our array: Add the following code and watch what happens to the variable x.

for( var x = 0; x < monsters.length; x++ ) { print( x ); }

Now, output the monster in each position

for( var x = 0; x < monsters.length; x++ ) { print( monsters[x] ); }
DO IT

Now, let's add a monster to the end of the list.

The push method will add a variable to the end of an array.

monsters.push("Spider"); for( var x = 0; x < monsters.length; x++ ) { print( monsters[x] ); }
DO IT
Try adding more than one string to the array: monsters.push("Spider");

In the next lesson, we will learn about Javascript objects

Get the Latest Tutorial Updates
<< >>
X