我有一个名为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 - 为什么不重新分配让点的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42474004/