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);
}
source to share
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.
source to share