These are the golden days of JavaScript, which was warily used in the not too distant past because of the browser wars (still being waged). With enhancements to JavaScript in recent years and the advent of AJAX, interest in Javascript has taken a new turn, a turn for the better. Early on with AJAX it was recognized that there was a contender for XML for handling data which was stable, faster, and portable. This was the beginning of JSON.
Unlike JSON objects, JSON arrays are enclosed between square braces [ ]. The JSON array is an ordered sequence of values separated by a comma (,). The values can be any of the primitive types as well as the two structures, JSON objects and JSON arrays. Here is a JSON array variable with four string values.
var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];
You will be able to access an array item from its position (0 based) as shown in the following listing.
<SCRIPT LANGUAGE="JavaScript">
var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];
for (i=0; i<4; i++){
document.write("<b>myJsonArray["+i+"]</b>="+ myJsonArray[i]+"<br>");
}
</SCRIPT>
The displayed output when this script is executed is as shown in the next picture.
It is possible to have an array whose elements are of different types. Array items can be objects and arrays as well, as shown in the next listing.
<SCRIPT LANGUAGE="JavaScript">
//Array with different types
myJA2=["red", 1, null, true];
document.write("<b>myJA2:</b> " + myJA2[2]);
document.write("<p></p>");
//Nested array
myJA3=["red",1,["a", "b", "c"], false];
document.write("<b>myJA3[2][1]:</b> " + myJA3[2][1]);
document.write("<p></p>");
//Object in an array
myJA4=["red", {"Yes":"Yes, you do", "No":"No, you do not"}, 2];
document.write("<b>myJA4[1].Yes: </b>"+ myJA4[1].Yes);
</SCRIPT>
The displayed output when this script is executed is as shown in the next picture. Notice how the inner array and the object inside the array are accessed.