Quick Reach
What is Array
An array is a type of variable that can store multiple values.
The array is a data structure that can hold one or more values in a single variable.
See an array example
Let us say, we want to store 50 US States in our jQuery program in a variable. What we can do is to create 50 simple variables:
var myvar1;
var myvar2;
And so on.
On the other hand, if you make that variable (myvar) an array in jQuery, you can store all 50 state names in a single variable.
How to declare an Array in jQuery
There are two ways to declare jQuery array:
An array with constructor
var State_Array = new Array( “NY”, “NJ” );
An array with literal declaration
var State_Array = [ “NY”, “NJ” ];
The Literal declaration is a preferred method to declare arrays in jQuery/JavaScript.
Basic Example of declaring and printing an array
Following example shows how to create a jQuery array (or JavaScript).
Experience this example online
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <html> <head> <title>jQuery Testing</title> <script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script> <script type=“text/javascript” language=“javascript”> // Using Foreach function printArray( Argu ) { document.write (Argu); } IntArray = [ 1, 2, 3, 4, 5 ]; // Prints all elements to the console IntArray.forEach( printArray ); </script> </head> </html> |
A few array functions and properties
Following are a few functions and a property of the array.
.length property
The length property of array jQuery is used to get the number of items in an array.
An example of using array length:
Experience this example online
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <html> <head> <title>jQuery Testing</title> <script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script> <script type=“text/javascript” language=“javascript”> var State_Array = [ “NY”, “NJ”, ]; document.write (State_Array.length); </script> </head> </html> |
You may need .length property to be used in For loops.
.reverse
It reverses the order of array elements.
Also see .forEach
Leave A Comment?