5

I have a nested loop that will work most of the time, but for one particular case it does not run at all.

Here is the value that is failing: 1, 3-5, 7-10, 22

JS code:

document.getElementById("myButton").addEventListener("click", function () {
    document.getElementById("msg").innerHTML = "";

    // Get the short list
    var list = document.getElementById("myIn").value;
    var sublists = list.split(", ");

    var Range = [];
    var result = "";
    var start;    // for the nested loop
    var end;      // for the nested loop

    for (var i = 0; i < sublists.length; i++) {
        Range = sublists[i].split("-");
        start = Range[0];
        end = Range[Range.length-1];

        Log("Range: " + Range);  // Shows which parts of the sublist the program sees

        for (var j = start; j <= end; j++) {
            result = result + j + ",";
            Log("Result in loop: " + result);  // Show which parts make it inside the loop
        }
    }

    result = result.slice(0, -1); // Takes off the extra comma at the end

    Log("Result: " + result);  // Shows result
});

When the failing value is entered, this is the result:

Range: 1
Result in loop: 1,
Range: 3,5
Result in loop: 1,3,
Result in loop: 1,3,4,
Result in loop: 1,3,4,5,
Range: 7,10   <--- Never goes inside the loop
Range: 22
Result in loop: 1,3,4,5,22,
Result: 1,3,4,5,22

I can't figure out why the 7-10 part is being skipped. Any help or explanation is greatly appreciated.

Here is the FIDDLE

2 Answers 2

14

You need use parseInt when work with integer here

start = parseInt(Range[0],10);
end = parseInt(Range[Range.length-1],10);

After splittng you get array with strings, and when you try compare "7" with "10" it compared as string and "7" always greater then "10", because char code for '7' greater than char code for '1' (first char in "10")

For converting to number you can use next function also: Number, parseInt or parseFloat

document.getElementById("myButton").addEventListener("click", function() {
  document.getElementById("msg").innerHTML = "";

  // Get the short list
  var list = document.getElementById("myIn").value;
  var sublists = list.split(", ");

  var Range = [];
  var result = "";
  var start; // for the nested loop
  var end; // for the nested loop

  for (var i = 0; i < sublists.length; i++) {
    Range = sublists[i].split("-");
    start = parseInt(Range[0], 10);
    end = parseInt(Range[Range.length - 1], 10);
    Log("Range: " + Range); // Shows which parts of the sublist the program sees

    for (var j = start; j <= end; j++) {
      result = result + j + ",";
      Log("Result in loop: " + result); // Show which parts make it inside the loop
    }
  }

  result = result.slice(0, -1); // Takes off the extra comma at the end

  Log("Result: " + result); // Shows result
});

// Log is my imitation of console.log()
function Log(stuff) {
  var msg = document.getElementById("msg");

  var newDiv = document.createElement("div");
  newDiv.innerHTML = stuff;

  msg.appendChild(newDiv);
}
<p>Try this value in the input: 1, 3-5, 7-10, 22</p>
<input id="myIn" type="text" />
<button id="myButton" type="button">Go</button>
<p id="msg"></p>

4
  • Thank you! Works like a charm. I will try to keep the different types of comparisons in mind. Apr 23, 2015 at 15:12
  • @Grundy - I'd made the jsFiddle before you had included your snippet. It was simply a working demo because you hadn't provided one.
    – Moob
    Apr 23, 2015 at 15:15
  • @Moob o, thanks, it seemed to me that you hint to an error :-)
    – Grundy
    Apr 23, 2015 at 15:18
  • 1
    @Grundy, Number is generally a safer method to use when converting strings to numbers unless you specifically need to either filter part of the string out or need to convert it with a non decimal radix. There are also other reasons for using parseInt with caution.
    – Jason Cust
    Apr 23, 2015 at 15:19
2

Since you are using a text input field all values from that field are strings. Then you use string manipulations that return more string values. You are never dealing with numbers. So Javascript will treat them as string values when testing if one value is greater than the other.

You can use the Number global object to safely cast a string value to a number. The benefit of Number over parseInt and parseFloat is if any part of the string is non numeric it will return a NaN value whereas the other two will return as much of the string as a number up to the first non-numeric character.

start = Number(Range[0]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.