为什么这个js循环在某个实例中被跳过了?

5

我有一个嵌套循环,大多数情况下都可以正常工作,但对于一个特定的情况,它根本不运行。

这里是失败的值:1, 3-5, 7-10, 22

JS代码:

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
});

输入失败的值时,将会得到如下结果:
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

我无法理解为什么跳过了7-10部分。非常感谢您的帮助和解释。
这里是FIDDLE
2个回答

14

在这里使用整数时,您需要使用parseInt

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

将字符串拆分成数组后,当您尝试比较"7""10"时,它会按照字符串比较,并且"7"始终大于"10",因为'7'的字符代码大于"10"中第一个字符'1'的字符代码。

要转换为数字,您还可以使用以下函数:NumberparseIntparseFloat

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>


谢谢!运行得很好。我会尽量记住不同类型的比较。 - UndoingTech
@Grundy - 在你添加代码片段之前,我已经创建了jsFiddle。这只是一个工作演示,因为你没有提供它。 - Moob
@Moob,谢谢,我感觉你在暗示一个错误 :-) - Grundy
1
@Grundy,通常情况下,将字符串转换为数字时使用Number方法更加安全,除非您需要过滤掉字符串的一部分或者需要使用非十进制基数进行转换。此外,还有其他原因需要谨慎使用parseInt方法。 - Jason Cust

2
由于您使用的是文本输入字段,因此从该字段获取的所有值都是字符串。然后您使用字符串操作返回更多的字符串值。您从未涉及数字。因此,当测试一个值是否大于另一个值时,Javascript将把它们视为字符串值。
您可以使用Number全局对象将字符串值安全地转换为数字。与parseIntparseFloat相比,Number的好处是,如果字符串的任何部分不是数字,则它将返回NaN值,而其他两个函数将返回字符串中到第一个非数字字符为止的尽可能多的数字。 start = Number(Range[0]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接