www.webdeveloper.com
Results 1 to 3 of 3

Thread: Array initialization

  1. #1
    Join Date
    Sep 2010
    Posts
    64

    Array initialization

    I can not get arr1 to initialize. I keep getting a null in the textbox sum.

    Code:
    <script type="text/javascript">
         function getarray(){
              var arr1 new Array(4);
              var arr1 = (1,2,3,4);
              var sum = 0;
              for (i=0; i<=3; i++){
                   sum = sum + arr1[i];
              }
         window.document.myform.sum.value = sum;
         }
    </script>
    Last edited by Philosophaie; 06-07-2012 at 05:42 PM.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,354

    Lightbulb

    Quote Originally Posted by Philosophaie View Post
    I can not get arr1 to initialize. I keep getting a null in the textbox sum.

    Code:
    <script type="text/javascript">
         function getarray(){
              var arr1 new Array(4);
              var arr1 = (1,2,3,4);
              var sum = 0;
              for (i=0; i<=3; i++){
                   sum = sum + arr1[i];
              }
         window.document.myform.sum.value = sum;
         }
    </script>
    Try...
    Code:
    <script type="text/javascript">
         function getarray(){
              var arr1 = [1,2,3,4];
              var sum = 0;
              for (i=0; i<arr1.length; i++){
                   sum = sum + arr1[i];
              }
           return sum;  // for testing
    //     window.document.myform.sum.value = sum;
         }
         alert(getarray());  // for testing
    </script>
    Note:
    1. You don't neet to initialize var arr1 twice.
    2. 1st var assignment needs an equal sign and does not need (4).
    3. 2nd var assignment is a short-cut assignment with [ ] characters.
    4. Reference element with [ ] characters, not ( ).
    5. You defined the function, but never called it to execute.

  3. #3
    Join Date
    Nov 2007
    Posts
    409
    Missing an "=" in your 'var arr1' line
    and use [] to indicate array items

    Code:
    <form name="myform">
    <input type="text" name="sum" value="">
    </form>
    <script type="text/javascript">
         function getarray(){
              var arr1 = new Array()
              var arr1 = [1,2,3,4];
              var sum = 0;
              for (i=0; i<=3; i++){
                   sum = sum + arr1[i];
              }
         window.document.myform.sum.value = sum;
         }
    getarray();
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles