Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have some lines of javascript as below:

C#
var start = str.split("-")[0];
var end = str.split("-")[1];
alert(start + " " + end);
for(strt=start;strt<=end;strt++)
{
    alert(strt);
}


Now, If i give value for str less than 10 i.e. 1-9, 7-9
or greater than equal to 10 i.e. 10-12, 10-15, 11-40 It works fine.. but of if I include 10 in between range i.e. 6-12, 8-12, 9-11 etc. It doesn't work.. I am unable to figure out.. still trying to debug... will anyone please join me to debug this out!

I fount the solution by breaking a case like 8-12 into parts to be processed like 8-9 and 10-12, but it'd be better if direct processing could be done.
Posted
Updated 31-Jul-14 9:25am
v2

1 solution

You're comparing string values instead of numbers. Since the character '6' is greater than the character '1', your loop will never execute.

Convert the values to numbers before processing them:
JavaScript
var str = "6-10";

var parts = str.split("-");
var start = parseInt(parts[0]);
var end = parseInt(parts[1]);

alert(start + "-" + end);

for (var strt = start; strt <= end; strt++)
{
    alert(strt);
}


http://jsfiddle.net/YrGHx/[^]
 
Share this answer
 
Comments
Manudhiman 31-Jul-14 15:29pm    
Thanks Buddy. I just skipped about parsing. hehe :P :)
RaisKazi 31-Jul-14 15:39pm    
Good Answer, my 5.
Sergey Alexandrovich Kryukov 31-Jul-14 15:49pm    
Well spotted, a 5.

The worst thing is the general trend of these days, at least in the beginners: to try to work with strings representing data. So, I suspect that the whole thing is not yet a reasonable solution. Where the "str" comes from? It's possible that it could be some data structure in first place, not yest another unreliable string...

—SA
[no name] 1-Aug-14 0:07am    
Nice answer, well found. My vote of 5. I used to have the same problem like this :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900