michaelmcgurk michaelmcgurk - 5 days ago 7
Javascript Question

Count total of values in variable in JS for loop

I have a

for
loop in my script that loops through a set of
markerNodes
results. I was wondering, how easy is it to create a
total
variable that adds up the integer value in
amount
& outputs at the end?

for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var amount = markerNodes[i].getAttribute("amount");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address, total);
bounds.extend(latlng);
}

Answer

Quite easy to add

var total = 0;
for (var i = 0; i < markerNodes.length; i++) {
   var name = markerNodes[i].getAttribute("name");
   var address = markerNodes[i].getAttribute("address");
   var amount = markerNodes[i].getAttribute("amount");

   total += parseFloat(amount);

   var distance = parseFloat(markerNodes[i].getAttribute("distance"));
   var latlng = new google.maps.LatLng(
        parseFloat(markerNodes[i].getAttribute("lat")),
        parseFloat(markerNodes[i].getAttribute("lng")));
   createOption(name, distance, i);
   createMarker(latlng, name, address, total);
   bounds.extend(latlng);
}

console.log(total);
Comments