我是javascript的新手。我試圖用下面的代碼給變量賦值,但失敗了。有人請幫忙指出我的代碼有什麼問題。變量的JavaScript設置值失敗
當我嘗試打印出變量「deviceLatitude」的值時,它給我「未定義」。但是,如果我從函數內部打印值,它會給我正確的值。我做錯了什麼?
我需要爲此值設置全局變量的原因是因爲我需要在後期使用它,例如根據需要比較不同位置的距離。
var deviceLatitude;
var deviceLongitude;
function suc (p) {
deviceLatitude = p.coords.latitude;
deviceLongitude = p.coords.longitude;
// alert(deviceLatitude);
}
intel.xdk.geolocation.getCurrentPosition(suc);
alert(deviceLatitude);
你在哪裏調用該函數?既然你不調用它,那變量的值實際上是未定義的。 – SVSchmidt
@SVSchmidt函數被'intel.xdk.geolocation.getCurrentPosition'調用回調。 –
是的,函數「suc」被「intel.xdk.geolocation.getCurrentPosition」調用。 @torazaburo,我已經定義了函數之外的變量,我只是把它的值添加進去,是不是錯誤?請指教。 – MarkZ