Javascript variables evaluating as undefined, but they should have values.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sebarry
    New Member
    • Jul 2007
    • 69

    #1

    Javascript variables evaluating as undefined, but they should have values.

    Hi,

    Code:
     
    
    var primaryKeyToKeyValue = new Array();
    	
    for(var i = 0; i < arguments.length; i++)
    {
         var len = document.getElementsByName(arguments[i])[0].options.length;
    		
         for( var j = 0; j < len; j++ )
         {
               if( document.getElementsByName(arguments[i])[0].options[j].selected )
               {
    	if( document.getElementsByName(arguments[i])[0].options[j].value !
                        = "-----" )
    	{
    	      primaryKeyToKeyValue[arguments[i]] = 
                              document.getElementsByName
                                  (arguments[i])[0].options[j].value;
    
                           alert( "Key is: " + primaryKeyToKeyValue[arguments[i]] );
    	}
                 }
           }
     }
    	
    alert( "Array is: " + primaryKeyToKeyValue );
    The value printed out for
    Code:
    key
    is
    Code:
    1
    although if I print out
    Code:
    arguments[i]
    the value printed out is the value of
    Code:
    arguments[i]
    .

    The value printed out for
    Code:
    Array
    is
    Code:
    undefined
    . What are the scoping rules for Javascript. It doesn't seem that changes to
    Code:
    primaryKeyToKeyValue
    during the for loops are not reflected at the end of the loop.

    Please help.

    Sean.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    you posted in the js-articles section ... i moved it over to the forum for you.

    kind regards

    Comment

    • si4
      New Member
      • Aug 2007
      • 5

      #3
      Hi,

      Here is nice article about variable scope in Javascript:


      Check your IFs statements, because if they are not TRUE neither of all loops you will not set the array any value.

      ( Sorry for the bad English )

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Changed thread title to better describe the problem (did you know that threads whose titles that do not follow the Posting Guidelines actually get FEWER responses?).

        Comment

        Working...