我的脚本中有一个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);
}
答案 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
);