If else conditions in Javascript
I have topdatedata value as 222
I have these 3 conditions specified
if((topDateDat开发者_开发问答a<250)&&(topDateData>25))
{
alert('one');
}
else if((topDateData>300)&&(topDateData<300))
{
alert('Two');
}
else
{
alert('Three');
}
My questions is why is it getting the value as alert(3) and not alert(one)??
When explicitly setting the value to 222
, I see 'one' get alerted: http://jsfiddle.net/Wvjfa/
You should debug your actual value ( alert(topDateData);
if you like) and see if it really is what you think it is.
Beyond that, Matt Ball is right, your second condition is borked. Also lonesomeday and Kerry are right about your variable case not matching between your question and the posted code.
Javascript is case sensitive, is topdatedata = 222
or topDateData = 222
?
it's much safer just to set one value - as you're second criteria looks dodgy
var topDateData = 222;
if(topDateData > 300)
{
alert('two');
}
else if(topDateData > 250)
{
alert('');
}
else if(topDateData > 25)
{
alert('One');
}
else
{
alert('Three');
}
start with the one that's hardest to satisfy (in this example the highest) and then work your way down. It's much easier to follow. Other than that it should work, as per the other comments on here
My guess is that you have a string.
var trueBool = '222' < '250'; //true
var falseBool = '222' > '25'; //false
To debug if topDateData is a String or not, do the following:
alert(topDateData + 1);//outputs '2221' if a string, and '223' if a number
Here's a fiddle showing the difference.
UPDATE:
I've tested alert(('222' < 250) && ('222' > 25));
and that outputs true
. However, I'm not sure all JavaScript compilers will be smart enough to convert the string to a number first. You should run the same test and see if true
is the output on your browser.
It looks like your topDateData variable contains a string value "222" instead of an integer.
You could try to cast to an integer this way:
topDateData = parseInt(topDateData);
...
精彩评论