If parseInt is used inside the 'for' loop, it works for all cases. But in this example, it is not working properly for cases like 99-100 or 999-1000. What happens here? Is the implicit conversion wrong?
function buggy10000(value)
{
var r = value.split("-");
var len=r.length;
var j;
if(len==2)
{
console.log("For in RANGE " + r[0]+"<-->"+r[1]);
for(j=r[0];j<=r[1];j++)
{
console.log(j);
}
}
}
buggy10000("98-99");
buggy10000("99-100"); //for not working as expected
buggy10000("100-102");
because: "98" <= "99" (string comparison)
"100" <= "102"
but "99" > "100"
The conversion appears only when j++ is called, but for the second case (99-100) that never happens, because the loop condition fails.
function buggy10000(value)
{
var r = value.split("-");
var len=r.length;
var j;
if(len==2)
{
console.log("For in RANGE " + r[0]+"<-->"+r[1]);
for(j=r[0]*1;j<=r[1]*1;j++) <----Modified
{
console.log(j);
}
}
}
Does it work?
parseInt() on the string. The OP has already said that works - Andrew Leach 2012-04-04 20:33
This is a type conversion problem, and it's related to comparisons. You're passing strings to your function, splitting the string, then comparing them. JS is getting confused as you're comparing strings, not integers.
I rewrote your function as follows to explicitly parse those values as integers, and it's working as you expect now.
function buggy10000(value)
{
var r = value.split("-");
var len=r.length;
var j;
if(len==2)
{
console.log("For in RANGE " + r[0]+"<-->"+r[1]);
r[0] = parseInt(r[0]);
r[1] = parseInt(r[1]);
for(j=r[0];j<=r[1];j++)
{
console.log(j);
}
}
}