Creating Arrays As You Go Along

If you're giving someone a quiz and want to store the answers in an array, you must create an array even though you don't know what values it will store. In such cases, you'll need to build your array piece by piece.

Start by creating an empty array, as in this line:

var the_answers = new Array();

This tells JavaScript to create a new array called the_answers, leaving it empty.

Once you've created the array, you can load values into it, like this:

the_answers[0] = "yes";
the_answers[1] = "no";
the_answers[2] = "maybe";

The first line puts the word yes into the first slot of the array, the next puts no into the second slot, and the third line puts maybe into the third slot. You can store values in an array in any order. ...

Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.