What's wrong with Multidimensional Array?


D

Dominik

--- Example 1
var myarray=[[],[]];
myarray[0][1]="NA"
print(myarray[0][1]); // output "NA"

--- Example 2
var myarray=[[],[]];
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
myarray[x][y]=0;
}
}

for (var x = 0; x < 5; x++)
print(myarray[x]); // output error myarray[x] is undefined !?!

What's wrong with example 2 ????
 
Ad

Advertisements

D

Dominik

var myarray=[[],[]];

myarray now has (empty) arrays at index 0 and 1.

--- Example 1.1
var myarray=[[],[]];
myarray[10][10]="NA"
print(myarray[10][10]); // output error myarray[10] is undefined

OMG What a mistake-a to make-a. :)
Thank you!

[snip]
At the third iteration, you're trying to set myarray[2][0] = 0.
myarray[2] is undefined, so you get an error.

You could create the child arrays when you need them, instead of doing
it in advance:

OK, I see it now.
But I'm curius, is it possible to create empty multidimensional array in
advance?
 
D

Dominik

Well, strictly speaking there's no such thing as a multidimensional
array in JS. There are only arrays of arrays. The two are often used in
a similar way, but there are differences. One of them is that there's no
way to initialize the child arrays with a simple statement*.

Thank you very much for your help. :)
 
T

Thomas 'PointedEars' Lahn

Stefan said:
In JS 1.7, you might use array comprehension to make the initialization
more concise:

var myarray = [[] for each (i in range(0, 4))];
// assuming a suitable range() generator function

Not very portable, though. If you need such arrays a lot, you may want
to define a function to handle the initializations.

Given that, according to my current research, Array comprehension is *only*
supported in (Mozilla) JavaScript 1.7 and later, I do not think it deserves
the attribute "portable" at all.


PointedEars
 
E

Evertjan.

Thomas 'PointedEars' Lahn wrote on 20 feb 2012 in comp.lang.javascript:
Given that, according to my current research, Array comprehension is
*only* supported in (Mozilla) JavaScript 1.7 and later, I do not think
it deserves the attribute "portable" at all.

I fail to comprehend the meaning of such atributable comprehension, Thomas.

Could you divulge?
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
OK, I see it now.
But I'm curius, is it possible to create empty multidimensional array in
advance?

One can assign a value to a variable which does not already exist.

For counting purposes, it would be useful to be able to increment a
variable which currently is value=undefined or is non-existent, with the
pre-increment value taken as either 0 or "", depending on the nature of
the increment. Possibly with X+++ and X ++= 7.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top