很抱歉,如果这是一个基本问题,但我很难理解如何做到这一点。
我正在尝试使用Google Places API通过匿名功能传递一系列乘客详细信息。我在任何地方都使用这个数组细节,所以我希望它可以在所有功能中使用。一旦我在getDetails中的匿名函数中,它就会丢失对i的引用。我真正想要做的是在displaydetails函数中获取i的值,这样我就可以在那里访问细节以在标记中显示它们。
任何人都可以给我一个关于如何做到这一点的指针吗?
提前致谢
var locations = [
['Mr Andrew Star', 35.776721, 140.392130, 'Tailor Made', '123456', 'ChIJVze90XnzImARoRp3YqEpbtU'],
['Miss Mary Jane', 35.684960, 139.761285, 'Group Tour', '123456', 'ChIJX1MLAgiMGGARBOTc8MbjVUU']
]
function displaydetails( place, status, image, i) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location,
title: locations[i][0] //not currently working
});
....
}
}
function placeMarkers() {
for (i = 0; i < location.length; i++) {
service.getDetails({
placeId: locations[i][5]
}, function (place, status) {
displaydetails(place, status, image, i);
});
}
}
答案 0 :(得分:0)
将'i'作为参数传递给函数:
function displaydetails( place, status, image, i) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location,
title: locations[i][0] //not currently working
});
....
}
}
答案 1 :(得分:0)
我试过了,我已将代码修改为我尝试的内容,因为我有点不清楚,抱歉。 '我'返回未定义......似乎价值正在迷失。我进行了大量的调试,并且在anonoymous函数之后,值似乎会丢失。
还有其他想法吗?
答案 2 :(得分:0)
尝试捕捉&#39; i的值,如下面的代码中所示。要了解其工作原理,请阅读this answer
中对闭包和值捕获的解释var locations = [ [&#39; Andrew Star先生&#39;,35.776721,140.392130,&#39; Tailor Made&#39;,&#39; 123456&#39;&#39; ChIJVze90XnzImARoRp3YqEpbtU&#39;], [&#39; Mary Jane&#39;,35.684960,139.761285,&#39; Group Tour&#39;,&#39; 123456&#39;,&#39; ChIJX1MLAgiMGGARBOTc8MbjVUU&#39;] ]
function displaydetails( place, status, image, i) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location,
title: locations[i][0] //not currently working
});
....
}
}
function placeMarkers() {
for (i = 0; i < location.length; i++) {
service.getDetails({
placeId: locations[i][5]
},
// This is the bit I've changed, to capture the current value of
// i and store it as captured_i
function(captured_i) {
return function (place, status) {
displaydetails(place, status, image, captured_i);
}
}(i));
}
}