2015-11-01 145 views
0

我有一個函數並創建了一個全局變量。Javascript全局變量爲空

函數內部的警報正在按照預期提醒結果,但變量沒有顯示任何內容。

我該如何解決這個問題?

下面的代碼:

var connectionResult = ''; 

function checkConnection() { 
    var networkState = navigator.connection.type; 

    var states = {}; 
    states[Connection.UNKNOWN] = 'Unknown connection'; 
    states[Connection.ETHERNET] = 'Ethernet connection'; 
    states[Connection.WIFI]  = 'WiFi connection'; 
    states[Connection.CELL_2G] = 'Cell 2G connection'; 
    states[Connection.CELL_3G] = 'Cell 3G connection'; 
    states[Connection.CELL_4G] = 'Cell 4G connection'; 
    states[Connection.CELL]  = 'Cell generic connection'; 
    states[Connection.NONE]  = 'No network connection'; 

    alert('Connection type: ' + states[networkState]); 

    var connectionResult = states[networkState]; 
}; 

checkConnection(); 

alert(connectionResult); // Returns Nothing 

回答

2

的問題是,你正在創建一個名爲connectionResult在checkConnection,而不是分配給全球connectionResult一個局部變量。

更換

var connectionResult = states[networkState]; 

connectionResult = states[networkState]; 

,它會工作。

擴展T.J.克羅德的評論如下,你可以使這個函數更高效一些,因爲你是一次又一次地聲明基本上是一個常量。無論你需要的連接狀態,你可以叫getConnectionState而不是一個全局變量左右浮動

var NetworkStates = {}; // this never changed in the old function, so refactored it out as a "constant" 
NetworkStates[Connection.UNKNOWN] = 'Unknown connection'; 
NetworkStates[Connection.ETHERNET] = 'Ethernet connection'; 
NetworkStates[Connection.WIFI]  = 'WiFi connection'; 
NetworkStates[Connection.CELL_2G] = 'Cell 2G connection'; 
NetworkStates[Connection.CELL_3G] = 'Cell 3G connection'; 
NetworkStates[Connection.CELL_4G] = 'Cell 4G connection'; 
NetworkStates[Connection.CELL]  = 'Cell generic connection'; 
NetworkStates[Connection.NONE]  = 'No network connection'; 

function getConnectionState() { 
    return NetworkStates[navigator.connection.type]; 
} 

現在:您可以如下更改代碼。

+0

確實。或者更好的辦法是讓'checkConnection' *返回它,並將結果分配給全局(理想情況下它不再是全局的)。 –

+0

Good call @ T.J.Crowder,我用你的建議更新了我的答案。 – syazdani

1

var connectionResult inside checkConnection創建一個新的變量叫做connectionResult

此「內部」變量僅在checkConnection範圍內。它隱藏或者打算使用"shadows"checkConnection中的任何對connectionResult的引用都會使用它來代替您期望的「外部」變量。

只是刪除var,你會使用現有的connectResult

connectionResult = states[networkState]; 
1
var connectionResult = states[networkState]; 

創建這是完全地無關的全局變量connectionResult

功能的範圍內,一個新的變量connectionResult只需使用

connectionResult = states[networkState]; 

爲了將網絡狀態分配給全局變量