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);
}​
1
  • because myarray[bla][bl] is not set... Commented Mar 14, 2012 at 20:32

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 - Kind of - there's actually a difference between JSON objects and javascript objects, as detailed here better than I ever could: 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: timdown.co.uk/jshashtable
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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.