Weird (but simple) issue with arrays

Discussion in 'JavaScript' started by ponar, Dec 20, 2007.

  1. #1
    Hey Guys,

    Look at the following code:

    
    var testArray = new Array();
    
    for(i=0;i<3;i++){
    	testArray[testArray.length] = new Array();
    	testArray[testArray.length][0] = "hello";
    }
    
    Code (markup):
    Everything works fine until we get to the last line in the for loop:
    testArray[testArray.length][0] = "hello";
    Code (markup):
    The weird thing is if I change that last line to:

    testArray[i][0] = "hello";
    Code (markup):
    it works fine. Can anyone help??? :(
     
    ponar, Dec 20, 2007 IP
  2. phper

    phper Active Member

    Messages:
    247
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    for(i=0;i<3;i++){
    	testArray[testArray.length] = new Array(); // Here you are adding an empty array to the end of testArray. So testArray.length is already incremented by 1 here 
    	testArray[testArray.length][0] = "hello";  // testArray.length here is no longer the same value as above
    }
    Code (markup):
    Either change testArray.length to i as you've tried before or combine the 2 lines in the loop to:
    testArray[testArray.length] = new Array("hello");
    Code (markup):
     
    phper, Dec 20, 2007 IP
    ponar likes this.
  3. ponar

    ponar Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Your a genius! I knew it was something simple that I was overlooking. Thank you, thank you, thank you!

    :D
     
    ponar, Dec 20, 2007 IP