Javascript array

Discussion in 'JavaScript' started by ruby, May 9, 2007.

  1. #1
    I am simulating a 4 dimensional array and am having a small issue which I can't seem to figure out.

    As an example:

    
    var test = [];
    
    test[0000] = 1;
    test[0100] = 2;
    
    a = 0+'';
    b = 0+'';
    c = 0+'';
    d = 0+'';
    
    e = a+b+c+d;
    
    alert(e);
    alert(test[e]);
    alert(test[0000]);
    
    Code (markup):



    If you run this javascript I get 3 alerts as follows:

    1) 0000
    2) Undefined
    3) 1



    Can anyone explain why that second alert is showing undefined when in theory it's the same as the 3rd one.
     
    ruby, May 9, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    I guess javascript is using associative arrays with strings, but treating e as a number, so test[e] is undefined.

    You can get it worked using strings explicitly:
    
    var test = [];
    
    test['0000'] = 1;
    test['0100'] = 2;
    
    a = '0'+'';
    b = '0'+'';
    c = '0'+'';
    d = '0'+'';
    
    e = a+b+c+d;
    
    alert(e);
    alert(test[e]);
    alert(test['0000']);	
    
    Code (markup):
     
    ajsa52, May 9, 2007 IP
    ruby likes this.
  3. ruby

    ruby Well-Known Member

    Messages:
    1,854
    Likes Received:
    40
    Best Answers:
    1
    Trophy Points:
    125
    #3
    heh.... of course, I'm an idiot.... but I guess its hard to think at 1am in the morning.

    rep added
     
    ruby, May 9, 2007 IP
  4. asfi

    asfi Peon

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    test[e] is declared wronglyl...
     
    asfi, May 10, 2007 IP