Javascript 全局数组在 JSON 结果函数中不可见
Javascript global array not visible in JSON result function
我有一个全局数组,在一个函数中我调用地理编码器 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);
}
知道为什么吗?谢谢。
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);
});
}
。诚然未经测试。但是,如果我正确地"音译"了它,那么您v
应该在该实现中正确限定范围。
不是你的回调看不到locationsArray
。如果是这种情况,您的错误会抱怨未定义locationsArray
或property 0 of locationsArray
。
真正的问题是,您的回调引用了 for 循环范围内的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
为了修复我们的示例,我们将"限定"对特定项目的引用并将其放在回调中。像这样:
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
相关文章:
- JScript 错误: 无法分配给函数结果
- 显示基于javascript函数结果的HTML代码
- 访问来自另一个函数的函数结果
- 将函数结果传递给Javascript中的另一个函数变量
- NaN作为函数结果而不是必需的整数出现问题
- 更改javascript更改函数结果的颜色
- 从函数结果中检测三角函数
- 根据函数结果使用 JavaScript 更改图像
- 如何返回函数结果并将它们设置为标记的内部 HTML
- JavaScript 如何将函数结果与数组中的值一起传递到同一个函数中
- 用
标记包装 JQuery 函数结果
- 节点函数结果未定义
- 使用Cheerio和Response for Node web scraper,将响应函数结果传递给视图
- 在所有项目javascript中显示函数结果
- 平板电脑友好的悬停工具提示,显示基于javascript函数结果的动态文本
- 在机器时间更改后立即更新Date()函数结果
- 屈服函数结果
- 如何在JavaScript中处理异步函数结果
- 声明和定义全局变量作为函数结果有时有效
- Jquery&函数结果,作为属性名称