3D Game Programming

(C. Jardin) #1

7.5 Listing Things


At times it’s quite handy to be able to describe a list of things. In JavaScript,
lists are made with square brackets. A list of amazing movies might look
something like this:

varamazing_movies = [
'Star Wars',
'The Empire Strikes Back',
'Indiana Jones and the Raiders of the Lost Ark'
];

The things in the list can be any of the kinds of things that we have talked
about so far: strings, numbers, Booleans. It is even possible to make a list
with various types of things:

// Don't do this:
varuseless_list = [
true,
3.14,
'OK'
];

But don’t do that. It’s silly. Just like in real life, computer lists should contain
the same kinds of things. It wouldn’t make sense to include your favorite
color, the time your friend is coming over, or the score of last night’s game
on a grocery list. A list of things to buy at the store should include only items
that are at the store.

There are lots of ways to use lists, but the one we’ll use the most in this book
is to call a function for each item in the list:

varamazing_movies = [
'Star Wars',
'The Empire Strikes Back',
'Indiana Jones and the Raiders of the Lost Ark'
];

amazing_movies.forEach(function(movie) {
console.log("GREAT: "+ movie);
});

Think of the forEach() function as a way of saying that “for each” thing in our
list,


  • give it a nickname—we call it movie in the preceding code

  • do stuff with it inside the function—we log it as "GREAT"


If you type this and check the JavaScript console, you’ll get back this output:


report erratum • discuss

Listing Things • 77


Prepared exclusively for Michael Powell

Free download pdf