我有一个嵌套循环,大多数情况下都可以使用,但是在特定情况下,它根本无法运行。
这是失败的值: 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
parseInt
在这里使用整数时需要使用
start = parseInt(Range[0],10);
end = parseInt(Range[Range.length-1],10);
splittng后,您将获得带有字符串的数组,并在尝试将“ 7”与“ 10”进行比较时,将其与字符串进行比较,而“ 7”始终大于“ 10”,因为“ 7”的字符代码大于“ 1”的字符代码(“ 10”中的第一个字符)
为了转换为数字,您还可以使用下一个函数:Number,parseInt或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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句