How to Use an Array Class in Javascript
To some, Javascript is often viewed as a primitive and not particularly useful programming language. However, Javascript is actually a fully object-oriented language that runs in your web browser. Among its many features are data structures such as arrays, ordered collections of variables. Using the array class is just like declaring any other type of variable.
Instructions
-
-
1
Declare an array variable. Since Javascript is loosely typed, variables simply hold values. While the values have a type, the variable itself does not have a type. Therefore declaring an array variable is much like declaring any other integer or string variable.var array = new Array();
-
2
Declare a variable with a known starting size. The above will create an empty array of indeterminate (or zero) length. While this may be your only option if you do not know how many elements the variable will contain, if you do know you can declare a variable using that information. This is preferable as resizing and array, which requires allocating new memory and moving the entire array, is computationally expensive.
-
-
3
Declare an array variable with a known starting size, by passing that size as an argument to the Array constructor.var array = new Array(34);
-
4
Pass the values as arguments to the array constructor (if the values will be known when you declare the array). This is faster and more compact than filling in the values later using the index operator.var names = new Array( "Jim", "Joe", "Bob");
-
5
Use array literals. Much like passing the array elements to the constructor, you can also use an array literal. This is functionally the same, but less verbose.var names = ["Jim", "Joe", "Bob"];
-
6
Push elements to the array. If the size and contents of the array are not known when the program is written, new elements can be "pushed" to the end of an array. To "push" an element onto an array is to make the array one element larger (if not already large enough) and to add the element to the end of the array.var names = new Array();names.push("Jim");names.push("Joe");names.push("Bob");
-
7
Modify and access elements of the array using the index operator. The index operator is the primary way of accessing array elements. Using the index operator (the square brackets), you can individually read or write any of the array elements.var names = new Array( "Jim", "Joe" );var name = names[0]; // Jimnames[1] = "Bob"; // Joe is now Bobnames[2] = "Carl"; // Array is expanded to hold Carl
-
8
Loop over an array. Looping over arrays can be achieved with the "for" loop. The size of the array can be read from the array's length attribute.var names = ["Jim", "Joe", "Bob"];for( var i = 0; i < names.length; i++ ) { document.write( names[i] );}
-
1