Skip navigation
JasonTheNerd
Currently Being Moderated

Summing Up An Array Of Numbers

Nov 30, 2012 8:34 PM

Tags: #flex-mobile #flex-4.6 #arrays

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?

 
Replies
  • Currently Being Moderated
    Dec 3, 2012 8:18 AM   in reply to JasonTheNerd

    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.

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points