Something wierd is happening in my javascript and i dont understand it. Can anyone explain?
var adsl2pSpeed = '9500 - 12500';
alert(adsl2pSpeed);
开发者_运维问答if (!adsl2pSpeed) {
alert(adsl2pSpeed);
var adsl2pSpeed = 'Unknown';
}
var speed = document.getElementById("PredictedSpeed");
speed.innerHTML = adsl2pSpeed + " b/s";
This alerts "Undefined" twice and sets the innerhtml to be "Unknown". If I comment out the if statment it alerts '9500 - 12500' and sets the innerHTML to be '9500 - 12500'. Whats happening? Is the string is being cast as an object so it becomes null?
EDIT : I am actually registing the adsl2pSpeed as a startup script not in the function. I moved it up for clarity but possibly that is the problem?
Speculation:
The indented code is in a function.
if (!adsl2pSpeed) {
alert(adsl2pSpeed);
var adsl2pSpeed = 'Unknown';
}
You are in that function declaring a local variable, which masks the global variable, so it looks "undefined".
Try to remove the var
to avoid making a new variable.
I think Thilo is right. If the code is in a function like:
var adsl2pSpeed = '9500 - 12500';
function test() {
alert(adsl2pSpeed);
if (!adsl2pSpeed) {
alert(adsl2pSpeed);
var adsl2pSpeed = 'Unknown';
}
var speed = document.getElementById("PredictedSpeed");
speed.innerHTML = adsl2pSpeed + " b/s";
}
// some code runs ...
test();
then the declaration of adsl2pSpeed
inside the if
-statement is "hoisted" to the top of the function, so that the function actually is interpreted like this:
function test() {
var adsl2pSpeed; // declaration hoisted to the top, shadows the global var
alert(adsl2pSpeed);
if (!adsl2pSpeed) {
alert(adsl2pSpeed);
adsl2pSpeed = 'Unknown'; // assignment to local var
}
var speed = document.getElementById("PredictedSpeed");
speed.innerHTML = adsl2pSpeed + " b/s";
}
This article explains it: http://bustingseams.blogspot.com/2009/08/another-javascript-pitfall-hoisting.html
精彩评论