JavaScript/Basics: Difference between revisions
wikademia>Hampshire2004 m Punctuation |
wikademia>Hampshire2004 Added a section on arrays |
||
| Line 61: | Line 61: | ||
====Arrays==== | ====Arrays==== | ||
Arrays in most languages are a means of collecting variables so that they can be referred to by an index. This is usually a numerical index beginning at 0(i.e., 0,1,2,...), but does not necessarily have to be a number. Arrays are declared in several ways; they can be declared either explicitly, indicating the number of variables in the array: | |||
var colors = new Array(7); | |||
or not: | |||
var colors = new Array(); | |||
In the last case, the programmer leaves the number of colors open-ended. This may allow him to be more flexible in the long run. | |||
To use a particular variable within the array, simply indicate the index of the element using brackets. : | |||
colors[2] = "orange"; | |||
x = colors[7] ; | |||
z = "The book's color is " + colors[5] + "."; | |||
It was mentioned before that arrays can use indexes other than numbers. One example of this might be using an index based on text instead of numbers. We might wish to index on the names of various fruits to get their colors: | |||
colors["lemon"] = "yellow"; | |||
colors["lime"] = "green"; | |||
colors["cherry"] = "red"; | |||
Programs can be made significantly more readable using this feature. | |||
document.write("The color of a cherry is " + colors[cherry] | |||
+ ", but the color of a lime is " + colors[lime]); | |||
===Operators=== | ===Operators=== | ||