Javascript循环跳过数组值

时间:2018-10-29 20:15:36

标签: javascript for-loop google-distancematrix-api

我正在尝试使用JavaScript进行for循环以遍历数组并为每个数组打印值。 它正在使用Google距离矩阵api寻找距离和持续时间。

我的代码在这里:https://codepen.io/claireben/pen/oaVoNG

var placesdest = ["11205", "11230", "11204", "11234", "33140", "90086"];
$(function() {
  for (var i = 0; i <= 6; i++) {

    function calculateDistance(origin, destination) {
      var service = new google.maps.DistanceMatrixService();
      service.getDistanceMatrix({
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
      }, callback);
    }

    function callback(response, status) {
      if (status != google.maps.DistanceMatrixStatus.OK) {
        $('.result').html(err);
      } else {
        var origin = response.originAddresses[0];
        var destination = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
          $('.result').html("Better get on a plane. There are no roads between " +
            origin + " and " + destination);
        } else {
          var distance = response.rows[0].elements[0].distance;
          var distance_value = distance.value;
          var distance_text = distance.text;
          var duration = response.rows[0].elements[0].duration;
          var duration_value = duration.value;
          var duration_text = duration.text;
          var miles = distance_text.substring(0, distance_text.length - 3);
          if (duration_value < 3600) {
            $('.result').html("It is " + distance_text + " from " + origin + " to " + destination + " AND " + duration_text);
          }
        }
      }
    }

    /*$('#distance_form').submit(function(e){
        event.preventDefault();
        var origin = $('#origin').val();
        var destination = $('#destination').val();
        var distance_text = calculateDistance(origin, destination);
    });*/

    //var origin = document.getElementById("originq").innerHTML;
    var origin = "1762 Gerritsen Ave Brooklyn, New York 11229";
    // var destination = document.getElementById("destinationq").innerHTML;
    var destination = placesdest[i];
    var distance_text = calculateDistance(origin, destination);

    var para = "<div class='result'></div>";
    $("body").append(para);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<h2>Distance Between two Addresses</h2>
<!--<form id="distance_form">
    <label>Origin: </label>
    <input id="origin" type="text" name="origin"/>
    <br/>
    <label>Destination: </label>
    <input id="destination" type="text" name="destination"/>
    <br/>
    <input type="submit" value="Calculate"/>
</form>-->
<div id="originq">1762 Gerritsen Ave Brooklyn, New York 11229
</div><div id="destinationq">1507 Coney Island Ave, Brooklyn, NY 11230
</div>

<div id="resultdura">
</div>

问题在于它没有遍历整个数组。似乎它随机选择了一个。

我是javascript新手。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的代码遇到的问题是由于循环的异步性质,而不是以某种方式处理它。有很多库,范例等可以解决此问题,但是要成为一名javascript专业人士,您必须要掌握一些东西。我将尝试描述该问题,以便您可以尝试在代码的上下文中解决该问题,而不是向您展示所有这些方法。

首先,我将描述运行该循环时发生的情况-它将触发6个请求,但是当这些请求返回响应数据时,哪个响应随哪个请求由您处理。

当您的请求从循环中被触发时,您可以像这样调用异步块:calculateDistance(origin,destination),然后在请求完成后将触发回调函数,您的原始循环如何传递到那个调用的calculateDistance函数中回调哪个请求去哪个结果?没有。

看看现有代码,运行循环的函数'init()'应该至少将索引变量i传递到calculateDistance(index,origin,distance)函数中,然后假设该函数可以使您执行以下操作:将其传递给回调函数,以便它可以匹配结果。您可能有一个具有相同大小的空数组,称为results,并且在回调函数中,如果在其中传递索引变量callback(response,status,index),则可以使用results[index] = response设置结果。然后,您必须跟踪所有请求的完成时间,然后呈现它们。

无论如何,这就是这里发生的事情,这是一个异步问题。关于它,有大量的读物,这是关于使用javascript进行编码的复杂事情之一。 Javascript是单线程的,因此了解异步范例很重要,在此我将不做所有描述。

答案 1 :(得分:-1)

希望这可以为您提供帮助

在for循环之前声明函数

var placesdest = ["11205", "11230", "11204", "11234", "33140", "90086"];
function calculateDistance(origin, destination) {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    $('.result').html(err);
  } else {
    var origin = response.originAddresses[0];
    var destination = response.destinationAddresses[0];
    if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
      $('.result').html("Better get on a plane. There are no roads between " 
                    + origin + " and " + destination);
    } else {
      var distance = response.rows[0].elements[0].distance;
      var distance_value = distance.value;
      var distance_text = distance.text;
      var duration = response.rows[0].elements[0].duration;
      var duration_value = duration.value;
      var duration_text = duration.text;
      var miles = distance_text.substring(0, distance_text.length - 3);
      // you are validating the duration_value to be more 3600 to be able print
      if (duration_value < 3600) {
        $('#resultdura').append("It is " + distance_text + " from " + origin + " to " + destination + " AND " + duration_text + " <br>");
      }
    }
  }
}

,然后创建一个函数以调用for

function init () {
  for (var i=0; i < placesdest.length; i++) {
    //var origin = document.getElementById("originq").innerHTML;
    var origin = "1762 Gerritsen Ave Brooklyn, New York 11229";
     // var destination = document.getElementById("destinationq").innerHTML;
    var destination = placesdest[i];
    var distance_text = calculateDistance(origin, destination);
  }
}

最后调用init方法初始化脚本

init()
  • 请记住,您正在验证要打印的持续时间,这意味着如果持续时间少于3600,并非所有目的地都将被打印