Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Arrays

An array is a collection of data values, just as an object is. While each data value contained in an object has a name, each data value in an array has a number, or index . In JavaScript, you retrieve a value from an array by enclosing an index within square brackets after the array name. For example, if an array is named a, and i is a non-negative integer, a[i] is an element of the array. Array indexes begin with zero. Thus, a[2] refers to the third element of the array a.

Arrays may contain any type of JavaScript data, including references to other arrays or to objects or functions. For example:

document.images[1].width

This code refers to the width property of an object stored in the second element of an array stored in the images property of the document object.

Note that the arrays described here differ from the associative arrays described in Section 3.5. The regular arrays we are discussing here are indexed by non-negative integers. Associative arrays are indexed by strings. Also note that JavaScript does not support multidimensional arrays, except as arrays of arrays. Finally, because JavaScript is an untyped language, the elements of an array do not all need to be of the same type, as they do in typed languages like Java. We’ll learn more about arrays in Chapter 9.

Creating Arrays

Arrays can be created with the Array( ) constructor function. Once created, any number of indexed elements can easily be assigned to the array:

var a = new Array( ); a[0] = 1.2; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata