Defining arrays
& multi-dimensional arrays using
literal notation
Up until JavaScript 1.2, defining an array meant the simple choice
between using
conventional
or
dense arrays. But there's a new kid in town, and it's showing up in
more and more scripts where arrays are used intensively. What could it be?
What else is there? In this tutorial, we look at literal notation- the
new-age way of defining an array.
Literal notation- an overview
Literal notation is a form of array declaration introduced in
JavaScript 1.2. Like the language version, it's supported by 4th+
generations of both IE and NS. In other words, all modern browsers.
To declare a literal notation (array), start out with square brackets,
then enclose each participating value inside, separated by commas:
var myarray=["Joe", "Bob", "Ken"]
Once declared, a literal notation behaves very much like a normal
array, so to call to Joe, you would use:
alert(myarray[0]) //Yo Joe what's up?
At this point, we can all discern at least one merit of literal
notation- its compact syntax . Literal notation puts even
dense arrays to shame when it comes to quickly declaring an array and
populating it with values.
Kinds of values literal notation accepts
Ok, moving on, lets explain the kind of values literal notation
supports. Apart from the obvious "string" and "numeric" input, you can
also use expressions:
var myarray=[x+y, 2, Math.round(z)]
If you can't make up your mind what to enter, undefined values are
accepted too, by using a comma (') in place of the value::
var myarray=[0,,,,5]
In the above, there are actually 6 array values, except the ones in the
center are all undefined. This is useful, for example, if you wish to come
back later to dynamically fill in these values, or set up your array for
future expansion.
|