我正在將一個可用的JS解決方案重新實現到Typescript中。 我有一個在緯度和經度上都有地理位置的對象數組。Typescript將其綁定到數組排序
我想根據他們的距離排序他們到一個特定的位置,currentLocation
。
我想存儲currentLocation
作爲一個私人屬性,並在排序函數內訪問它。但是,在執行this.currentLocation
時,這在compare
中未定義。我試過compare.bind(this)
,但沒有成功。 this is not defined
。
任何想法如何解決這個問題?我用全局變量在JS中解決了這個問題,但這並不優雅。 sortByDistance
是一種對象方法。
sortByDistance() {
this.currentPosition = Leaflet.latLng(this._currentLatLng[0], this._currentLatLng[1]);
function compare(a, b) {
let p1 = Leaflet.latLng(a.lat, a.lng);
let p2 = Leaflet.latLng(b.lat, b.lng);
if (p1.distanceTo(this.currentPosition) < p2.distanceTo(this.currentPosition))
return -1;
else if (p1.distanceTo(this.currentPosition) > p2.distanceTo(this.currentPosition))
return 1;
return 0;
}
compare.bind(this);
this.sorted = this.objects.sort(compare);
}
謝謝,就是這樣。 –