3 Replies Latest reply: Dec 3, 2012 8:18 PM by JasonTheNerd RSS

    Summing Up An Array Of Numbers

    JasonTheNerd

      I have an array of numbers and am trying to write a function to sum them up and set a bindable variable to the sum. Any suggestions guys?

        • 1. Re: Summing Up An Array Of Numbers
          JasonTheNerd Community Member

          Here's what I came up with. Not the most elegant, but I'd love to here suggestions...

           

           

          protected function sumItemArray():void

                                        {

             

                                                       for (var i:int = 0; i < itemsArray.length; i++) {

                                                             CurrentPreTax = CurrentPreTax + itemsArray[i];

                                                       }

                                        }

           

          • 2. Re: Summing Up An Array Of Numbers
            pauland Community Member

            Never a good idea to name variables starting with a capital (only name Classes with a capital and camel-case). Always good to initialise and declare them and far better to return the total and pass in the array to iterate through.

             

            protected function sumArray( arr:Array):Number

                                          {

                                                    var arrTotal:Number = 0.0;

                                                    for (var i:int = 0; i < arr.length; i++) {

                                                               arrTotal = arrTotal + arr[i];

                                                         }

                                                    return arrTotal;

                                          }

             

            Then call it as

             

            currentPreTax = sumArray(itemsArray);

             

            Better to write generic functions, where possible, that are self-sufficient - not dependent on variables outside their declaration.

            • 3. Re: Summing Up An Array Of Numbers
              JasonTheNerd Community Member

              Much more elegant! Thank you for your help!