[英]How to get sum of all value in for loop JavaScript?
I tried calculate distance of truck marker on google map. 我试过计算谷歌地图上卡车标记的距离。
var Total=0;
var json = result.d;
obj = JSON.parse(json);
for (var i = 0; i < obj.length; i++)
{
var LatLng1 = new google.maps.LatLng(obj[i].Lat, obj[i].Lng);
var LatLng2 = new google.maps.LatLng(obj[i+1].Lat, obj[i+1].Lng);
var Distance=(google.maps.geometry.spherical.computeDistanceBetween(LatLng1, LatLng2) / 1000).toFixed(2);
Total+=Distance;
alert(Total); //It is working but.Like this : 0.01 0.22 0.03 0.045
// I want to be 0.01+0.022+0.03+....=Total
}
alert(Total); //Does not working !!
I get this error at console : TypeError: obj[(i + 1)] is undefined.
我在控制台收到此错误: TypeError: obj[(i + 1)] is undefined.
Where is my wrong ? 我哪里错了?
Your loop condition is i < obj.length
你的循环条件是i < obj.length
However, later in your code, you're using obj[i+1]
. 但是,在稍后的代码中,您将使用obj[i+1]
。
As a consequence, on your last interation, you'll be using obj[obj.length]
. 结果,在最后一次交互中,您将使用obj[obj.length]
。
To solve your problem, you either have to do one less iteration or to have a special case for the end of your array. 要解决您的问题,您要么必须减少一次迭代,要么在数组末尾有特殊情况。 The choice depends on what you seek to achieve (eg : you may want to have the distance between the last and the first). 选择取决于您要达到的目标(例如:您可能希望在最后一个和第一个之间保持距离)。
Try this code: 试试这个代码:
var Total=0;
var json = result.d;
obj = JSON.parse(json);
for (var i = 0; i < obj.length -1; i++)
{
var LatLng1 = new google.maps.LatLng(obj[i].Lat, obj[i].Lng);
var LatLng2 = new google.maps.LatLng(obj[i+1].Lat, obj[i+1].Lng);
var Distance=(google.maps.geometry.spherical.computeDistanceBetween(LatLng1, LatLng2) / 1000);
Total+=Distance;
}
alert(Total); //It will work
The reason it wasn't working earlier is that you got an exception everytime you accessed element at obj.length index. 它不能更早地工作的原因是,每次访问obj.length索引中的元素时都会出现异常。 I guess you didn't look into developer tools in your browser to find the exception. 我猜您没有在浏览器中使用开发人员工具来发现异常。
Your are trying to access obj[i+1] but i+1 = length in the last iteration. 您正在尝试访问obj [i + 1],但i + 1 =上一次迭代的长度。 You should iterate from 0 to obj.lenght-1. 您应该从0迭代到obj.lenght-1。
Your code must be: 您的代码必须是:
var Total = 0;
var json = result.d;
obj = JSON.parse(json);
for (var i = 0; i < obj.length-1; i++) { // Max is length-1 !
var LatLng1 = new google.maps.LatLng(obj[i].Lat, obj[i].Lng);
var LatLng2 = new google.maps.LatLng(obj[i + 1].Lat, obj[i + 1].Lng);
var Distance = (google.maps.geometry.spherical.computeDistanceBetween(LatLng1, LatLng2) / 1000).toFixed(2);
Total += Distance;
alert(Total);
}
alert(Total);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.