Naming, defining, and accessing arrays

Naming an array

The rules for naming arrays are the same as for naming variables, functions, and objects.
You have to avoid the following three things: numbers as the first character, spaces, and reserved words.

Defining an array

Defining an array is very similar to creating an instance of an object.

var ArrayName = new Array(element0,element1);

You replace ArrayName with the actual name you want to give to your array, and element0 and element1 with the values that each element will have.

var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");

The names of the students are stored inside an array that has four elements.
The names are between quotation marks because they are strings.

Accessing an array’s element

Accessing array elements is usually done with an index number. Basically, the index number is the element’s position in the array.

var VariableName = ArrayName[0];

Note:
Arrays begin storing values with the number 0 rather than 1.

You would replace VariableName with the name you want to give to the variable and the ArrayName with the name of the array you want to access. [0] is the first element in the array.

//Assigning the array's element to a variable
var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");
var VnStud = StudentsClass[0];
document.write("The Vietnamese student in the class is "+VnStud);

//Without assigning the array's element to a variable
var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");
document.write("The Vietnamese student in the class is "+StudentsClass[0]);

Leave a Reply