Getting Sum of Variables in JS

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • npm
    New Member
    • Apr 2007
    • 57

    Getting Sum of Variables in JS

    Hi,
    I have javascripts that display the number of radio stations from my xml files. I'm in need of a javascript that can add all the variables and then display the grand total. I looked on W3Schools's JS Math section and I couldn't find a section on addition.

    Here's my individual scripts that display each state's # of stations:
    Code:
    <script type="text/javascript">
    	xmlDoc=loadXMLDoc("stationsAK.xml");
    	x1=xmlDoc.getElementsByTagName('city');
    	document.write("Total Stations: " + x1.length);
    </script><br />
    <script type="text/javascript">
    	xmlDoc=loadXMLDoc("stationsAL.xml");
    	x2=xmlDoc.getElementsByTagName('city');
    	document.write("Total Stations: " + x2.length);
    </script><br />
    etc...all the way to:

    Code:
    <script type="text/javascript">
    	xmlDoc=loadXMLDoc("stationsWY.xml");
    	x50=xmlDoc.getElementsByTagName('city');
    	document.write("Total Stations: " + x50.length);
    </script>
    I just need a script that can take the "length" of all the variables (x1 through x50) and return the total # of stations from all 50 states.

    I'm assuming it's something like this:
    Code:
    <script type="text/javascript">
      document.write(Math.sum(x1,x2,....,x50))
    </script>
    Thanks in advance!
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    hi ...

    that will not work ... but you may use a simple function that does the trick for your purpose, define the following FIRST:

    [CODE=javascript]
    <script type="text/javascript">
    var total_stations = 0;

    function add_stations(va l) {
    total_stations += val;
    }
    </script>
    [/CODE]
    and everytime you use document.write you call the func to add the station-no:

    [CODE=javascript]
    <script type="text/javascript">
    xmlDoc =loadXMLDoc("st ationsWY.xml");

    var x50 = xmlDoc.getEleme ntsByTagName('c ity');
    var stations = x50.length;

    document.write( "Total Stations: " + stations);

    add_stations(st ations);
    </script>
    [/CODE]
    now the global var total_stations has the sum of all stations assigned and you may alert or write it ... or whatever you want to do with it ;)

    kind regards

    Comment

    • npm
      New Member
      • Apr 2007
      • 57

      #3
      Hi,
      Sorry it took so long to get back on your reply, this project/experiment had to be put on the back burner for a while.

      But it worked great! Thanks!

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        glad to hear that ;) ... post back to the forum anytime you have more questions ...

        kind regards

        Comment

        Working...