PDA

View Full Version : JavaScript and Multidimensional Arrays


SixtySoftWorks
2004.01.03, 01:37 PM
The following code always returns a value of 3 on my Mac. How can I have my script return "4"?


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title>Untitled</title>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF">

<script>
var test = new Array()
test[1,1] = "1"
test[1,2] = "2"
test[2,1] = "3"
test[2,2] = "4"
test[3,1] = "5"
test[3,2] = "6"
test[4,1] = "7"
test[4,2] = "8"
document.write(test.length)
</script>

</body>
</html>

Steven
2004.01.03, 02:25 PM
Multidimensional arrays are accessed as array[x][y], not array[x,y]. The comma operator works as follows: if you have x,y it returns y. So, array[x,y] is the same as array[y]. That's why you have only 3 elements - you set 1 and 2 repeatedly. Also, remember that arrays are 0 based.

SixtySoftWorks
2004.01.04, 05:19 AM
It should work, thanks.