简体   繁体   English

JavaScript for 循环值未在循环内部更新

[英]JavaScript for loop value not updating inside of loop

I am working on project dealing with the Google Maps API and I am trying to get the duration between multiple trips and tell what trips are shorter based on time.我正在研究处理谷歌地图 API 的项目,我正在尝试获取多次旅行之间的持续时间,并根据时间判断哪些旅行更短。 I was getting weird values in my object so I put some print statements outside of the directionsService and inside of it to.我在 object 中得到了奇怪的值,所以我将一些打印语句放在了方向服务之外和里面。 Code:代码:

  //loop through all the trips being made
  for (i = 0; i < destinationsArray.length; i++) {
    //request holds the information for the directions request
    var request = {
      origin: destinationsArray[i].from, 
      destination: destinationsArray[i].to, 
      travelMode: google.maps.TravelMode.TRANSIT,
      transitOptions: {
        modes: ['BUS'],
        routingPreference: 'LESS_WALKING',
        arrivalTime: today.now, 
      } 
     }
     let directionsService = new google.maps.DirectionsService();
     let companyID = destinationsArray[i].id;
     console.log(i + " outside")
     directionsService.route(request, function(reponse, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        console.log(i + " inside")
        //create a new direction render for clickable options
        let dirRender = new google.maps.DirectionsRenderer({map: map});
        //push this new direction render onto the array 
        directionsRenderers.push(dirRender)
        //create object to hold data about this current trip: trip length and company name
        let tripInformation = {duration: reponse.routes[0].legs[0].duration.value, id: companyID}
        //put this var into array
        //console.log(tripInformation)
        durationArray.push(tripInformation)
        //this line puts the trip onto the map to see
        directionsRenderer.setDirections(reponse);
      } else {
        alert("Could not display directions due to: " + status);
      }
    }
  );
  }

the print statements are coming out like so: 0 outside 1 outside 0 inside 0 inside打印语句的输出如下: 0 外 1 外 0 内 0 内

the destinationsArray is here if needed:如果需要,destinationsArray 在这里:

var destinationsArray = [
  {id: "Trip 1", to: "John Ball Park Zoo", from: "Rosa Parks Circle"},
  {id: "Trip 2", to: "10897 48th Ave NW", from: "1 Campus Drive Allendale"}
];

Consider this code:考虑这段代码:

 for(x = 0; x < 5; ++x) { setTimeout(() => console.log(x)) // Outputs 5, 5, 5, 5, 5 }

Versus this:与此相反:

 for(let x = 0; x < 5; ++x) { setTimeout(() => console.log(x)) // Outputs 0, 1, 2, 3, 4 }

Please see here for detailed explanation详细解释请看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM