Skip to content Skip to sidebar Skip to footer

Array Of Array Returning Nan

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

Solution 1:

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" issetto the emptyarray 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.

Solution 2:

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

Solution 3:

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

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

Post a Comment for "Array Of Array Returning Nan"