Creating multi-dimensional arrays using literal notation
The thing about defining multi-dimensional arrays using the standard
syntax is that we're often the ones taken into the next dimension before
the process is over. Or is it just me? At any rate, literal notation
simplifies things for everyone, as it supports nesting of other literal
notation. This makes defining multi-dimensional arrays extremely easy and
intuitive. The following example uses literal notation to define a array
with 3 elements, the 1st element being a 2 dimensional array:
var myarray=[["New York", "LA", "Seattle"], China, Japan]
Yes, it's that easy. By merely using another literal notation as one of
the array values, we add a 2nd dimension to that particular element. Let's
go to "LA" shall we:
myarray[0][1] //returns "LA"
Just to demonstrate literal notation's' versatility in this respect,
here's an array with its 1st element in turn being a 3 dimensional array:
var myarray=[[[2,4,6]], China, Japan]
Just remember, the more brackets you use, the deeper the hole you dig!
Wrapping it up...
Hopefully you've developed a familiarity to and appreciation for
literal notation in this tutorial. Since literal notation is supported
only by JavaScript 1.2 and up, it's a good idea to declare the language
version inside the script that takes advantage of it to ensure legacy
browsers just ignore the entire script.
<script language="JavaScript1.2">
var yourarray=[234, "good", 18]
"
</script>
To conclude this tutorial, here two example scripts that use literal
notation:
1)
JavaScript Graph It
2)
NosTree
|