I have the following code:
<html>
<body>
<div style="background-color: lightblue;" onClick="alert(myArray[0][1])">
this is a div
</div>
<script type="text/javascript">
var myArray = new Array();
myArray[0][0] = 0;
myArray[0][1] = 00012;
myArray[0][2] = 00006;
myArray[1][0] = 1;
myArray[1][1] = 00004;
myArray[1][2] = 00001;
</script>
</body>
</html>
When I click on the div, nothing happens; there’s no alert. When I change the inside of alert to a string, such as ‘test’, however, then the alert box does come up.
What am I doing wrong? How can I get the value of an item in a multidimensional array?
Thanks!
The first line of your code:
…will create a new, single dimensional array,
myArray, that has no elements. Then when you say:…you are trying to access a dimension that doesn’t exist yet. That is,
myArray[0]isundefinedbecause althoughmyArrayis an array it doesn’t have any elements yet – somyArray[0][0]is like sayingundefined[0].That’s why you have to to assign
myArray[0]to refer to a new array before you can accessmyArray[0][0]. The same thing applies tomyArray[1], because JavaScript doesn’t have multi-dimensional arrays per se, it has arrays of arrays. So this is what you need (for a minimal change to your existing code):Note that
[]is equivalent tonew Array().An easier to read and type option is to create the sub-arrays via array literal syntax:
Or, easiest of all (especially if these are hard-coded values) is creating the whole thing in one statement via a nested array literal (white-space is ignored):
(Note also that those leading zeros will disappear for numeric data: use strings (
"00012"instead of00012) if you want to retain the zeros.)