Creating Your Own Arrays

Arrays are so handy that you'll often want to create your own. A phone book, for example, is an array of names and phone numbers. You can think of a survey as an array of questions; an array can also store the answers a visitor enters. A slide show is an array of pictures shown in sequence.

Happily, JavaScript lets you create your own arrays. If you know what you want to store in the array when you create it, use a line like the following:

var rainbow_colors =
    new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");

This line creates a variable called rainbow_colors that stores an array of colors. The words new Array() tell JavaScript to create a new Array object, just as new Date() created a new Date object ...

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.