Why am I getting undefined error in my array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jen O
    New Member
    • Nov 2010
    • 2

    #1

    Why am I getting undefined error in my array?

    Code:
    <script>
    		window.onload=myday;
    			
    			function myday(){
    				
    			var day=new Array("sunday","monday","tuesday","wednesday","thursday","friday","saturday");
    			
    			var d=new Date();
    			theDay=d.getDay();
    			
    			for (i=0;i<=day.length;i++)
    			{
    					if (i!=theDay)
    				{
    				
    				document.write("today is not " + day[i]);
    				document.write("<br />");}
    				
    				else
    				{
    					document.write("today is " + day[i]);
    					document.write("<br />");}
    			}
    			}
    			
    			
    </script>
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    because you use document.write( ).

    if you call document.write( ) after the page finished loading (i.e. when onload is triggered) document.write( ) erases* the current document (completely) and writes the document anew. at that point all your JavaScript has been erased and thus your function is not defined.


    * - it does that by implicitly calling document.open()

    Comment

    • Jen O
      New Member
      • Nov 2010
      • 2

      #3
      How do you recommend I get around this? I have this example from my book(below), and it uses the onload with document.write. I believe this is why I am confused.

      Code:
      <script type="text/javascript">
      	window.onload=initAll;
      
      	function initAll(){
      	var allmonths = new Array ("january","february","march","april","may","june","july","august","september","october","november","december")
      	var birthmonth = prompt("what is your birth month?","");
      	for(i=0;i<allmonths.length;i++){
      		if (allmonths[i]==birthmonth){
      			document.write("<strong>"+(i+1)+". "+allmonths[i]+" is your birth month!"+"</strong></br >");
      			alert("Hooray "+allmonths[i]+" is your birth month!");
      		} else{
      			document.write((i+1)+". "+allmonths[i]+" is "+"<strong>"+"NOT"+"</strong>"+" your birth month!"+"</br >");
      		}
      	}
      
      }
      	</script>
      Last edited by Dormilich; Nov 9 '10, 02:55 PM. Reason: please use [CODE] [/CODE] tags when posting code

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        It's a very small error. In your for loop you have for (i=0;i<=day.len gth;i++)

        but if you compare this to your example for(i=0;i<allmo nths.length;i++ ) you will notice the operator <= should be <.

        You want your loop to terminate before 'i' is equal to the length. This is because arrays start at 0. If you have an array with length of 5 you would have indexes 0,1,2,3,4 but not 5.

        Comment

        Working...