我是 JavaScript 的新手。我正在尝试使用以下代码将值设置为变量但失败了。有人请帮助指出我的代码有什么问题。
当我尝试打印出变量“deviceLatitude”的值时,它给我“undefined”。但是如果我从函数内部打印值,它会给我正确的值。我做错了什么?
我需要为此值设置全局变量的原因是因为我需要在后期使用它,例如根据需要将距离与不同位置进行比较。
var deviceLatitude;
var deviceLongitude;
function suc (p) {
deviceLatitude = p.coords.latitude;
deviceLongitude = p.coords.longitude;
// alert(deviceLatitude);
}
intel.xdk.geolocation.getCurrentPosition(suc);
alert(deviceLatitude);
最佳答案
suc
被异步回调,所以当您在调用 intel.xdk....
后发出警报时,suc
还没有被调用。
注意文档,我强调的是:
Use this command to get the current location. This command asynchronously acquires the approximate latitude and longitude of the device. When data is available, the success function is called. If there is an error getting position data, the error function is called.
因此,如果您想对 deviceLatitude
执行某些操作,则必须在 回调中执行。
如果你是一个 promise 类型的人,你可以这样做:
function getCurrentPosition() {
return new Promise(function(resolve, reject) {
intel.xdk.geolocation.getCurrentPosition(resolve, reject);
});
}
getCurrentPosition.then(
function(p) {
//do something with p.coords.latitude
},
function() {
//something went wrong
}
);
关于变量的 JavaScript 设置值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843009/