[thelist] 2-dimensional array in jscript

liorean liorean at gmail.com
Thu Sep 2 11:53:45 CDT 2004


On Thu, 02 Sep 2004 08:33:26 -0700 (PDT), aspscript at canada.com
<aspscript at canada.com> wrote:
> I am trying to create a 2-dimensional array without having to set the upper bounds of the second parameter.
 
> I *thought* I could create a two-dimensional array with
> this:
>     var arr = [][]
> But that gives an error.

Yeah. Arrays are first class objects in JavaScript. JavaScript arrays
are dynamically sized and type independent. Two dimensional arrays in
JavaScript are simply arrays where the elements in the outer array are
also arrays.

> So I've been just setting an upper limit of 100 and doing this to create the array:
>     x = []
>     for (k=0;k<100;k++){
>         x[k] = []
>     }
> Is there a way to set the array without having to declare an upper limit to the second part? Thanks for any help!

Well, how do you want your final two dimensional array to look? I
guess you by "setting" the array mean filling it with values.  How do
you mean that you don't want to limit the second part, if you want to
fill it with values? Or do you by "setting" the array mean just
defining it?

Anyway, what I wanted to lift forth here, is that Arrays are not
locked at any specific size in JavaScript, and may contain any type of
object, not just a specific kind. That means that a two dimensional
array differs in no way from any other array. Arrays do not work like
in some compiled, strictly typed languages, where arrays are typed and
fixed sized.

Take this example, for instance:
    var
        arr=[],
        i=3;
    do
        arr.push([]); // Add element to array, assign a new array to it
    while(0<--i); // And repeat two times, generating a three element array;

After doing that, you have an array looking like this:
    [
        [],
        [],
        []].
  
Then you can fill each of the contained arrays with whatever you wish.
Or you can assign a new value to a element in the outer.
    arr[1]="blah";
    arr[4]=[1,2];
 
After which you have an array looking like this:
    [
        [],
        "blah",
        [],
        undefined, // Not just undefined but undeclared meaning it
doesn't exist at all.
        [1,2]]

So, JavaScript arrays are a fair bit more dynamic than for example the
type of arrays you find in C is. But then they happen to be far closer
to both hash tables and dynamically linked lists in both structure and
performance than they are to arrays in C.

Well, I don't know if that helped or not, but it might explain a thing or two.
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>


More information about the thelist mailing list