2014-07-19 70 views
1

我是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); 
+0

你在哪裏調用該函數?既然你不調用它,那變量的值實際上是未定義的。 – SVSchmidt

+0

@SVSchmidt函數被'intel.xdk.geolocation.getCurrentPosition'調用回調。 –

+0

是的,函數「suc」被「intel.xdk.geolocation.getCurrentPosition」調用。 @torazaburo,我已經定義了函數之外的變量,我只是把它的值添加進去,是不是錯誤?請指教。 – MarkZ

回答

1

正如@torazaburo所指出的那樣,不可能將異步數據變成全局變量。

但是爲了實現所需,解決方法可以解決這個問題。由於這是HTML5應用程序,因此可以使用localStorage來保存該值並隨後從其他屏幕/功能隨時訪問它。

一個簡單的例子代碼將如下:

intel.xdk.geolocation.getCurrentPosition(
      function(p) { 
       if (p.coords.latitude != undefined) { 
        localStorage.deviceLatitude = p.coords.latitude; 
        localStorage.deviceLongitude = p.coords.longitude; 
       } 
      }, 
      function() { 
       alert("geolocation failed"); 
      } 
     ); 
2

suc被稱爲異步回,所以當你調用intel.xdk....之後發出警報,suc尚未調用呢。

注意的文檔,我的重點:

使用此命令來獲取當前位置。該命令 異步獲取 設備的近似經度和緯度。當數據可用時,調用成功功能。如果 獲取位置數據出錯,則調用錯誤函數。

因此,如果你想要做的事與deviceLatitude,你必須做回調。

如果你是一個承諾類型的球員,你可以這樣做:

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 
    } 
); 
+0

無論如何將價值作爲全球變量帶出來嗎? – MarkZ

+0

不,你不能把它作爲一個全局變量出現,直到它被設置。 :-) –

+0

好吧。謝謝... – MarkZ

2

嘗試做出錯誤的成功和其他匿名函數。 然後創建另一個函數,當數據可用時將通過異步調用。

function overrideLocalStore(lat, log) 
{ 
    alert("lat"+lat+" long"+long); 
    localStorage.setItem("deviceLatitude", lat); 
    localStorage.setItem("deviceLongitude", log); 
} 

intel.xdk.geolocation.getCurrentPosition(
    function(p) 
    { 
     alert("geolocation success"); 
     if (p.coords.latitude != undefined) 
      overrideLocalStore(p.coords.latitude, p.coords.longitude); 
    }, 
    function() 
    { 
     alert("geolocation failed"); 
     getLocation(); 
    } 
); 

// Use whatever you need 
alert(localStorage.getItem("deviceLatitude")); 
alert(localStorage.getItem("deviceLongitude")); 
+0

嗨@LXSoft,謝謝,我也試過。它不工作。當我嘗試在回調函數外面打印變量時,我仍然得到「未定義」。 – MarkZ

+1

您可以嘗試存儲會話對象嗎?來自ovverideGlobals的功能?然後,您可以訪問商店對象中的變量,這很奇怪,我的工作與您的問題相同,但使用Google Maps API將其存儲在會話變量中。 – LXSoft

+0

好主意。謝謝你給我這樣的想法。我將它寫入本地存儲和成功。非常感謝。現在我可以使用任何我想要的值。 – MarkZ