Chapter 6: Programming with Arrays


An array is a series of variables with the same name. Individual values, also called elements, in the series are accessed using an index. You can think of an array as a table with a column. The column contains cells, and in each cell is a value. You can save data to a cell, or retrieve data from the cell, using the row number (or index) in the table.

In JavaScript, arrays are all single-dimensional, meaning that they fit this single table column pattern. By contrast, in many other programming languages you can have multidimensional arrays. Multidimensional arrays use multiple indices to access their values, so (for example) a two-dimensional array can be pictured as a table with rows and columns.

Although all arrays in JavaScript are one-dimensional, you can achieve much the same effect as that of a multidimensional array using arrays of arrays, as I show you later in this chapter.

In the real world, programming usually involves groups of objects. Arrays are specifically designed to store groups of objects (the objects are retrieved using the index). Arrays are important because they make it possible to easily scale your code—meaning they deal in an automated fashion with the vast amount of data presented by the real world.

It’s common to first write a function (or program) to deal with a single instance of a value. The function can then be generalized, using an array, to deal with many instances of the same type.

Once you have the code working for a single value, it takes little additional work to create code that processes all the values in an array—so in this way it doesn’t take much more work to write code that processes many values after you’ve written the code that processes the first value. (Another way of saying this, in jargon, is that “the program easily scales.”)

In the “ Using a Function’s Arguments Array ” section in Chapter 5, “ Understanding Functions,” I showed you how to use the arguments array associated with any JavaScript function. If you go back and have a look at the example in that section, you’ll see that using the function’s argument array was a pretty intuitive affair. This chapter takes a bit more formal approach to arrays because they’re so important to most programs.

To start with, I show you how to create and populate arrays. Next, you’ll learn how to iterate through arrays, implement data structures using arrays, and work with arrays of arrays. Along the way, I show you how to use methods associated with arrays. Finally, I show you how to program with the JavaScript elements array associated with every HTML form.

Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: