3

So why myarray[bla][bl] always equal to NaN? If I do the same thing with 1 dimension (myarray[bla]), I get the number.

var bla = 'blabla';
var bl = 'bla';
var myarray = [];
for (i = 0; i < 10; i++) {
    if (!myarray[bla]) {
        myarray[bla] = [];
    }
    myarray[bla][bl] += i;
    console.log(myarray[bla][bl] + " + " + i);
}​
David
  • 325
  • 1
  • 3
  • 11

3 Answers3

3

Ok, so let's step through your loop, replacing instances of the variable bla with the string value of 'blabla':

if (!myarray['blabla']) {
  myarray['blabla'] = [];
}

Arrays in javascript are index by integer values. What your code here is doing is adding an expando property to the array instance named blabla. That is:

myarray.blabla = [];

now reconsider your increment statement:

myarray['blabla'][bl] += i;

or, with the expando properties:

myarray.blabla.bl  // remember that "myarray.blabla" is set to the empty array above

What this is trying to do is access the property named bl on the empty array. That's why you're getting undefined here.

Anyway, as a best practice, you might want to avoid using arrays in javascript like hashtables, since problems like this are bound to crop up after enough time.

matt
  • 9,113
  • 3
  • 44
  • 46
  • Best practice for hashtables in javascript would be JSON I guess? I come from a perl background where hashes are all you need to know. – David Mar 14 '12 at 20:45
  • @David - Kind of - there's actually a difference between JSON objects and javascript objects, as detailed here better than I ever could: http://stackoverflow.com/questions/6489783/ - but in general, yeah, you can sometimes use simple object instances as hashtables. One notable exception where this *won't* work is where your hashtable key type is something other than a simple string - like a custom object type. This page has some nice explanations of why objects/arrays act the way they do: http://www.timdown.co.uk/jshashtable/ – matt Mar 14 '12 at 21:14
0

If we expand a little I hope you can see the problem,

if (!myarray[bla]) {
    myarray[bla] = [];
}
myarray[bla][bl] = myarray[bla][bl] + i;

Hint: myarray[bla][bl] = undefined

Andrew
  • 13,757
  • 13
  • 66
  • 84
0

because myarray[bla][bl] is not set... , you need

if ( !myarray[bla][bl] ){ myarray[bla][bl] = 0; }
scibuff
  • 13,377
  • 2
  • 27
  • 30