在JS for循环中计算变量中的值的总和

时间:2016-11-28 15:46:31

标签: javascript

我的脚本中有一个for循环,循环显示一组markerNodes个结果。我想知道,创建一个total变量来增加amount&中的整数值是多么容易最后的输出?

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);
}

2 个答案:

答案 0 :(得分:2)

很容易添加

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);

答案 1 :(得分:0)

这是另一种方法。 (通过使用Array.reduce)

var total = Array.prototype.reduce.call(
   markerNodes, 
   (prev, cur) => prev + Number(cur.getAttribute("amount")), 
   0
);