PDA

View Full Version : JavaScript and Multidimensional Arrays (Part 2)


SixtySoftWorks
2004.01.07, 12:46 PM
It's the same code, and it doesn't work yet.


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

<script>
toast = new Array()
toast[0][0] = "0,0"
toast[0][1] = "0,1"
toast[0][2] = "0,2"
toast[0][3] = "0,3"
toast[1][0] = "1,0"
toast[1][1] = "1,1"
toast[1][2] = "1,2"
toast[1][3] = "1,3"
toast[2][0] = "2,0"
toast[2][1] = "2,1"
toast[2][2] = "2,2"
toast[2][3] = "2,3"
toast[3][0] = "3,0"
toast[3][1] = "3,1"
toast[3][2] = "3,2"
toast[3][3] = "3,3"
document.write(toast[2][2])
</script>

</body>
</html>


:blush:

Taxxodium
2004.01.07, 01:37 PM
try this

replace:


toast = new Array();


with:


rows = 4; cols = 4;
toast = new Array(cols);

for (i = 0; i < rows; i++)
toast[i] = new Array(cols);

SixtySoftWorks
2004.01.07, 01:40 PM
Okay, it's working fine. What exactly is that code? A workaround to some missing or misprogrammed JavaScript feature mb?

SixtySoftWorks
2004.01.07, 01:43 PM
Also, I guess that about 70% of the JavaScript Core Reference 2 (written by the Netscape guys) should be rewritten. Most examples documented there aren't actually working. :mad:

Taxxodium
2004.01.07, 05:14 PM
that code is how you make 2D arrays in JavaScript. I don't think there are other ways.

Steven
2004.01.07, 08:42 PM
The code makes an array of 4 elements, and for each of these elements assigns another array to it. That's how you do dynamically allocated multi-dimensional arrays in C, just slightly different.

Codemattic
2004.01.07, 11:45 PM
small nit:
toast = new Array(cols); should read:
toast = new Array(rows); it only works the way you have it b/c both rows and cols are the same number (4).
hth,
Codemattic

SixtySoftWorks
2004.01.10, 08:00 AM
Wait a second.
1) What if I have an array with 5 colums and 2 rows or something like that?
2) How can I avoid initializing the "rows" and "cols" vars each time?
3) This prevents me from having more than a multidimensional array on the same page, right?