提问者:小点点

Javascript返回值在循环中只返回一次


我创建了这个函数来计算我要测量的距离:

distanceToResponder: function() {
    var distance = 0;
    var incidentLocation = this.createCoordinate(this.currentIncident["latitude"], this.currentIncident["longitude"]);

    this.responders.forEach(function(responder) {
        var responderLocation = this.createCoordinate(responder.location.latitude, responder.location.longitude);
        distance = this.calculateDistanceBetweenLocations(incidentLocation, responderLocation);
    }.bind(this));
    return distance;
}

由于我不明白的原因,距离的值只返回一次。因此,如果我在forEach函数中抛出2个位置,并且在循环中使用console.log,我会看到所有的计算都是正确的。但如果我返回距离的值,则只返回一个值。

如何正确返回值?

我使用VueJS,其中'Distance toResponder'是一个计算属性来填充表:

   <tr v-for="responder in responders">
        <td>{{ responder.userReference }}</td>
        <td>{{ distanceToResponder(responder) }}</td>
        <td><button type="button" class="btn btn-danger" @click="createDispatch(responder)">Alarm</button></td>
    </tr>

因此函数应该返回每个响应者的距离。那么我需要如何调整我的功能呢?


共2个答案

匿名用户

您正在迭代您的响应器,并且每次覆盖距离。然后在迭代之后将该距离返回到最后一个响应程序。

    var distances = this.responders.map(function(responder) {
      var responderLocation = this.createCoordinate(responder.location.latitude, responder.location.longitude);
      return this.calculateDistanceBetweenLocations(incidentLocation, responderLocation);
    }.bind(this));
    return distances;

由此创建一个计算属性“distanceResponders”。并且在模板中

 <tr v-for="(index, responder) in responders">
    <td>{{ responder.userReference }}</td>
    <td>{{ distancesToResponder[index] }}</td>
    <td><button type="button" class="btn btn-danger" @click="createDispatch(responder)">Alarm</button></td>
</tr>

或者创建“增强的”响应程序计算属性:

 respondersWithDistance: function() {

  var incidentLocation = this.createCoordinate(this.currentIncident["latitude"], this.currentIncident["longitude"]);

  return this.responders.map(function(responder) {
    var responderLocation = this.createCoordinate(responder.location.latitude, responder.location.longitude);
    responder.distance = this.calculateDistanceBetweenLocations(incidentLocation, responderLocation);
 }.bind(this));
}

并在模板中也使用它:

 <tr v-for="responder in respondersWithDistance">
    <td>{{ responder.userReference }}</td>
    <td>{{ responder.distance }}</td>
    <td><button type="button" class="btn btn-danger" @click="createDispatch(responder)">Alarm</button></td>
</tr>

匿名用户

除了外部most函数调用之外,这里根本没有使用返回值。您的内部foreach回调只设置两个函数共享的单个变量(distance)的状态,最终返回该变量。

foreach的每次迭代都会覆盖distance的前一个值,以便只留下最终值。

不清楚“返回多个”是什么意思,因为函数可能只返回一个值,但可以使用map而不是foreach返回距离数组:

distanceToResponder: function() {
    var incidentLocation = this.createCoordinate(this.currentIncident["latitude"], this.currentIncident["longitude"]);

    return this.responders.map(function(responder) {
        var responderLocation = this.createCoordinate(responder.location.latitude, responder.location.longitude);
        return this.calculateDistanceBetweenLocations(incidentLocation, responderLocation);
    }.bind(this));

}