我有一个函数并创建了一个全局变量。
函数内的警报按预期提醒结果,但变量未显示任何内容。
我该如何解决这个问题?
代码如下:
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
问题是你在checkConnection中创建一个名为connectionResult的局部变量,而不是分配给全局连接结果。
取代
var connectionResult = states[networkState];
跟
connectionResult = states[networkState];
它会起作用。
为了扩展下面 T.J. Crowder 的评论,你可以使这个函数更有效一点,因为你一遍又一遍地声明本质上是一个常量。您可以按如下方式更改代码:
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,而不是让全局变量浮动。
var connectionResult = states[networkState];
在函数范围内创建一个与全局变量connectionResult
完全无关的新变量connectionResult
只需使用
connectionResult = states[networkState];
为了将网络状态分配给全局变量
>checkConnection
内部var connectionResult
创建一个名为connectionResult
的新变量。
这个"内部"变量仅在checkConnection
内部范围内。它隐藏或"阴影"您打算使用的变量:任何对connectionResult
内部checkConnection
引用都会使用它而不是您期望的"外部"变量。
只需删除var
,您将使用现有connectResult
:
connectionResult = states[networkState];