Unlike most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements:
scores = new Array(4);
To assign a value to the array, you use an index in brackets. Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These statements assign values to the four elements of the array:
scores[0] = 39; scores[1] = 40; scores[2] = 100; scores[3] = 49;
You can also declare an array and specify values for elements at the same time. This statement creates the same scores array in a single line:
scores = new Array(39,40,100,49);
In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents. The following statement is an alternative way to create the scores array:
scores = [39,40,100,49];
An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
2:
3:
var languages = ["php", "javascript", "java", "action script"]; document.write(languages.slice(0,1) + "
"); document.write(languages.slice(1) + "
"); document.write(languages.slice(-2) + "
"); document.write(languages);
nums = new Array(30, 10, 200, 4); sortednums = nums.sort(num);
var a = [1,2,3];
a.pop(); //-> 3
a; //-> [1,2]
var a = [1,2];
a.push(3, 4); //-> 4
a; //-> [1,2,3,4]