Accessing array from outside of geocode loop

心不动则不痛 提交于 2019-12-01 10:57:11

When your codeAddress function returns, geocoder.geocode is still doing its job, which is asynchronous. When geocoder.geocode is done, it will invoke its callback, which you're passing as an anonymous function.

The solution I suggest is to make the callback function a parameter of codeAddress, and do whatever you need from that callback (or from other function called inside the callback), instead of using the global variables approach.

It's all about scope in Javascript. If you want to access variables outside of the function, you must declare and create variables outside of the function scope and then update them.

Variables declared outside of the function scope will be available anywhere else within the script.

 var def = "bombshell";
 function changer(){
     def = "changed value";
 }
 changer();
 alert(def);

See it here - http://jsfiddle.net/daveheward/kWn8b/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!