javascript - 为什么let点的值没有被重新分配

标签 javascript angular typescript angular2-services

我有一个名为 point 的变量,它会更新以保存某个位置的 lat 和 lng 值。但是,当我在 if 函数内重新分配时,point 的值不会更新。一旦进入 if 函数,point 的值就会被重新分配并打印正确的值,但是当它离开 if 函数时,它又会回到未定义状态。

generateWayPoint(address: string): string {
  let point;
  const point4 = new google.maps.LatLng(51.496144, -3.182328);

  const geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'address': address }, function (results, status) {

    if (status === google.maps.GeocoderStatus.OK) {

      point = new google.maps.LatLng(results[0].geometry.location.lat(),
                                     results[0].geometry.location.lng());
      this.wayPoint = point;
      console.log('a point in the making', this.wayPoint);
      console.log('a wayPoint in the making', this.wayPoint);

    } else {
      console.log('Geocode was not successful for the followin reason:', status);

    }
  });


  console.log('a point how it should be:', point4);
  console.log('comparing a point', point);
  console.log('comparing a wayPoint', this.wayPoint);
  return point;

}

最佳答案

这与let无关。

地理编码函数被称为异步,因此在它第一次打印点时,它实际上没有被分配。

关于javascript - 为什么let点的值没有被重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42474004/

相关文章:

javascript - Coffeescript、Haml 等模板引擎

javascript - 在 AngularJs 中获取 JSON 文件的大小返回错误的值

angular - 当我使用 ng build 时停止要求收集分析的 Angular cli

javascript - Firebase 更新嵌套数组中的对象

Angular 2(2.0.0 到 2.2.0~)在使用 "import ' 反射元数据行添加自定义装饰器时出错”

javascript - 无法打印到控制台

javascript - 在一次 API 调用后设置延迟 5 秒

javascript - 如何转换 YYYY-MM-DDT00 :00:00 to YYYY/MM/DD in javascript?

javascript - 使用 Angular Router 获取 URL

javascript - 如何使用 jQuery 获取 div.id 的innerHTML(动态更新)