Javascript全局变量为空

时间:2015-11-01 18:56:35

标签: 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

3 个答案:

答案 0 :(得分:2)

问题是您在checkConnection中创建了一个名为connectionResult的局部变量,而不是分配给全局connectionResult。

替换

var connectionResult = states[networkState];

connectionResult = states[networkState];

它会起作用。

扩展T.J.下面的克劳德的评论,你可以使这个功能更有效率,因为你一遍又一遍地声明本质上是一个常数。您可以按如下方式更改代码:

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];
}

现在,只要你需要连接状态,你就可以调用getConnectionState而不是浮动一个全局变量。

答案 1 :(得分:1)

var connectionResult内{p> checkConnection创建一个名为connectionResult变量。

此“内部”变量仅在checkConnection内的范围内。它会隐藏或"shadows"您打算使用的内容:connectionResult内对checkConnection的任何引用都会使用它而不是您期望的“外部”变量。

只需删除var即可使用现有的connectResult

connectionResult = states[networkState];

答案 2 :(得分:1)

var connectionResult = states[networkState];

在函数范围内创建一个新变量connectionResult,该变量与全局变量connectionResult

完全无关

只需使用

connectionResult = states[networkState];

以便将网络状态分配给全局变量