Array array returning NaN

So why is myarray [bla] [bl] always NaN? If I do the same with 1 dimension (myarray [bla]) I get a 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);
}​

      

+3
javascript


source to share


3 answers


So let's walk through your loop by replacing the variable instances with bla

a string value 'blabla'

:

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

      

Arrays in javascript are indices on integer values. What your code here does is add an expando property to an array instance named blabla

. I.e:

myarray.blabla = [];

      

now revisiting the increment operator:



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

      

or using 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 named property on bl

an empty array. This is why you are getting undefined

here.

Anyway, as a best practice, you may want to avoid using arrays in javascript like hashtables, as such problems inevitably arise after enough time.

+3


source to share


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

0


source to share


because myarray[bla][bl]

not installed ... you need

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

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics