计算 3 点之间距离的传单 - 在 javascript 数组对象中搜索

问题描述

我想从总距离中减去到传单航点的距离。我该怎么做?

routes: Array(1)
0:
coordinates: (379) [D,D,…]
inputWaypoints: (3) [i,i,i]
instructions: Array(25)
0: {type: "Head",distance: 32.9,time: 6.4,road: "85200. Sokak",direction: "NE",…}
1: {type: "Right",distance: 88.2,time: 14.8,road: "85211. Sokak",direction: "SE",…}
2: {type: "Right",distance: 1045.9,time: 154.7,road: "",direction: "SW",…}
3: {type: "EndOfRoad",distance: 300.3,time: 27,direction: "W",…}
4: {type: "SlightLeft",distance: 314.5,time: 22,direction: "NW",…}
5: {type: "Right",distance: 31.8,time: 11.1,direction: "N",…}
6: {type: "Left",distance: 158.1,time: 14.3,…}
7: {type: "WaypointReached",distance: 0,time: 0,…}
8: {type: "Head",distance: 793.8,time: 77.7,…}
9: {type: "EndOfRoad",distance: 91.2,time: 11.5,…}
10: {type: "Right",distance: 840.6,time: 77.2,direction: "E",…}
11: {type: "Right",distance: 150.9,time: 13.5,…}
12: {type: "Right",distance: 206.1,time: 18.4,direction: "S",…}
13: {type: "Straight",distance: 1022.5,time: 67,…}
14: {type: "Continue",distance: 1320.5,time: 91.8,…}
15: {type: "Left",distance: 201.4,time: 16,…}
16: {type: "Fork",distance: 577,time: 46,…}
17: {type: "Merge",distance: 10006.4,time: 400.4,…}
18: {type: "OffRamp",distance: 765,time: 61.2,…}
19: {type: "Left",distance: 1106.4,time: 51.4,…}
20: {type: "SlightLeft",distance: 7236.4,time: 308.6,…}
21: {type: "OffRamp",distance: 105.9,time: 9.5,…}
22: {type: "Continue",distance: 737.9,time: 48.3,…}
23: {type: "SlightLeft",distance: 1397.8,time: 125.9,…}
24: {type: "DestinationReached",…}
length: 25
__proto__: Array(0)

我可以找到第 7 个索引。 “到达航点”

var test = e.routes[0].instructions.filter(o => {return o.type === 'WaypointReached'});

但我需要的是索引 0,1,2,3,4,5,6 的距离之和。

例如:

0=> distance: 32.9
1=> distance: 88.2
2=> distance: 1045.9
3=> distance: 300.3
. . .
6=> distance: 158.1

总距离= 1971,7

我该怎么做?有没有更简单的方法

解决方法

js break 关键字指示循环停止执行。它在情况下很有用 您只想处理满足条件的一组数据。

let distanceSum = 0;

for(let i = 0; i < e.routes[0].instructions.length; i++) {
  // Stop running the loop when the type is WaypointReached.
  if (e.routes[0].instructions[i].type === "WaypointReached") {
    break;
  }
  distanceSum += e.routes[0].instructions[i].distance;
}

console.log(distanceSum);

上面的代码和下面的逻辑类似,但是更透明。

let distanceSum = 0;
let i = 0;
while(i < e.routes[0].instructions.length && e.routes[0].instructions[i].type !== "WaypointReached") {
  distanceSum += e.routes[0].instructions[i].distance;
  i++;
}

break 关键字仅在实际循环、开关和标签内有效。也就是说,它在Array.prototype.reduce等数组迭代方法中没有任何作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...