我有一个全局数组,在函数中我调用了地理编码器api。问题是数组在结果函数中不可见。 我收到错误消息:
Uncaught TypeError: Cannot set property 'address' of undefined
以下是代码:
var locationsArray = new Array();
function GetAddress(){
for(var i=0;i<locationsArray.length;i++)
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="+locationsArray[i].position.lat()+','+locationsArray[i].position.lng(), function (result) {
locationsArray[i].address = result.results[0].formatted_address;
});
console.log(locationsArray);
}
知道为什么吗?感谢。
答案 0 :(得分:1)
<强> TL; DR 强>
为什么你没有使用.each()?你似乎还在使用jQuery ......
function GetAddress() {
$.each(loationsArray, function(i, v) {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ v.position.lat() + ',' + v.position.lng(),
function (result) {
v.address = result.results[0].formatted_address;
}
);
console.log(v);
});
}
......诚然未经考验。但是,如果我已经音译了#34;正确地说,您的v
应该在该实现中适当确定范围。
并非你的回调无法看到locationsArray
。如果是这种情况,那么您的错误就会抱怨locationsArray
或property 0 of locationsArray
未被定义。
真正的问题是,你的回调是指来自for-loop范围的i
。在最后一次迭代之后,它实际上将i
增加为locationsArray.length
。测试循环条件,失败,并退出循环。但是,i
仍然是locationsArray.length
- 一个从未存在过的值。 (但是,在相关问题中,在回调触发之前,集合也可以进行修改。)
让我们举个例子:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(i, arr, arr[i]);
}, i * 100);
}
Chrome控制台将显示以下内容:
> 3 [1, 2, 3] undefined
> 3 [1, 2, 3] undefined
> 3 [1, 2, 3] undefined
为了解决我们的例子,我们将&#34;范围&#34;对特定项的引用,并将 放入我们的回调中。像这样:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// create a scope
(function() {
var v = arr[i];
setTimeout(function() {
console.log(v);
}, i * 100);
})();
}
......控制台显示:
> 1
> 2
> 3