gpt4 book ai didi

javascript - 将状态传递给 JavaScript 中的子函数?

转载 作者:行者123 更新时间:2023-12-02 18:10:11 25 4
gpt4 key购买 nike

我有一组尝试用不同颜色渲染的方向。我向 Google 请求指示,但我不确定如何存储状态,以便返回路由结果时我可以以正确的颜色呈现每个结果。

所以,作为一个例子,我有这个对象:

{routes: [{start_lat : 0.0, start_lng : 0.0, end_lat : 1.0, end_lng : 1.0, color : "#ff0000"},
{start_lat : 1.0, start_lng : 1.0, end_lat : 2.0, end_lng : 2.0, color : "#00ff00"}]}

这是我的功能:

directionsService = new google.maps.DirectionsService();
for(var i = 0; i < routes.length; i++){
var dir_request = {
origin : new google.maps.LatLng(routes[i]['start_lat'], routes[i]['stop_lng']),
destination : new google.maps.LatLng(routes[i]['end_lat'], routes[i]['end_lng']),
travelMode : google.maps.TravelMode.WALKING
};
directionsService.route(dir_request, function(result, status) {
if(status == google.maps.DirectionsStatus.OK){
// render with custom logic depending on which route this is here
}
})
}

如何将状态(例如 for 循环中的索引)附加到每个请求,以便可以从结果处理函数访问它?

最佳答案

您需要使用closure scoped variables要做到这一点。当您尝试在路由回调函数中使用 i 时,您正在使用称为闭包的概念,其中父函数中声明的变量可以从内部函数访问。

但是使用 closures in a loop有它自己的问题,因为闭包变量的相同实例将在循环内创建的所有内部函数之间共享,因此当调用内部函数时,您将获得分配给循环中变量的最后一个值。

这里的解决方案是在循环内创建一个局部闭包,如下所示

directionsService = new google.maps.DirectionsService();
for (var i = 0; i < routes.length; i++) {
(function (idx) {
var dir_request = {
origin: new google.maps.LatLng(routes[idx]['start_lat'], routes[idx]['stop_lng']),
destination: new google.maps.LatLng(routes[idx]['end_lat'], routes[idx]['end_lng']),
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(dir_request, function (result, status) {
// the variable idx will refer to the array index for the current iteration
if (status == google.maps.DirectionsStatus.OK) {
// render with custom logic depending on which route this is here
}
})
})(i)
}

关于javascript - 将状态传递给 JavaScript 中的子函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19781038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com