gpt4 book ai didi

javascript - 为什么在一个实例中跳过了这个 js 循环?

转载 作者:数据小太阳 更新时间:2023-10-29 05:44:13 25 4
gpt4 key购买 nike

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

这是失败的值: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 , parseIntparseFloat

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>

关于javascript - 为什么在一个实例中跳过了这个 js 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com