gpt4 book ai didi

javascript - 为什么这个javascript无限循环?

转载 作者:行者123 更新时间:2023-11-28 11:13:42 25 4
gpt4 key购买 nike

方法 constructBuilder() 不应该无限循环,因为它被设置为仅循环 10 次,并且 data.length 的值永远不会改变。

这个循环和方法实际上工作得很好,直到我在循环中调用另一个方法。

当我在这个循环内调用方法getOptions(type)时,i的值发生非常奇怪的变化,并且始终遵循以下模式:

1st run: i=0
2nd run: i=1
3rd run: i=3
4th run: i=5
5th run: i=6
6th run: i=4
7th run: i=4
8th run: i=4
nth run: i=4

i 的值停留在 4,不增加并且循环无限运行!

为什么会出现这种情况?

这是代码:

var data = [["Text Array", "Some more text", "btnText", "btn2text"],
["Text2", "2: more text", "btnText2", "btn2text2"],
...
];

var products, order;

function initialise() {
products = loadProducts();
order = new Order();
constructBuilder();
}

function constructBuilder() {
var qb_boxes_innerHTML = "";
for (i=0; i<data.length; i++) {
alert("i="+i + "; data length="+data.length);
var box_innerHTML = "<table width=100% height=100% cellpadding=0; cellspacing=0; border=0>";
box_innerHTML += "<tr><td width=100% height=\"50px\">" + data[i][0] + "</td></tr>";
box_innerHTML += "<tr><td width=100% class=\"scroll\" valign=\"top\">" + data[i][1] + getOptions(i) + "</td></tr>";
box_innerHTML += "<tr><td width=100% height=\"50px\" align=\"right\" valign=\"middle\"><form action=\"javascript:next();\"><input type=\"button\" value=\""
+ data[i][2] + "\" onClick=\"prev();\"/><input id=\"continueBtn\" type=\"submit\" value=\""
+ data[i][3] + "\" disabled/></form></td></tr>";
box_innerHTML += "</table>";
qb_boxes_innerHTML += "<div id=\"qb_box" + i + "\" class=\"qb_box\" style=\"visibility: hidden;\">" + box_innerHTML + "</div>";
}
document.getElementById("qb_boxes").innerHTML = qb_boxes_innerHTML;
document.getElementById("qb_box0").style.visibility = "";
}
function getOptions(type) {
var optionsList = getProducts(products, type);
var options_html = "";
for (i=0; i<optionsList.length; i++) {
options_html += "<input id=\"check"+type+"_"+i+"\" type=\"checkbox\"/>" + optionsList[i].name + "<BR/>";
}
return options_html;
}

function getProducts(productList, type) {
var productsOfType = new Array();
for (i=0; i<productList.length; i++) {
if (productList[i].type == type)
productsOfType.push(productList[i]);
}
return productsOfType;
}

如果您需要更多信息,请评论。

感谢您的浏览。

最佳答案

通过使用不带 vari,您实际上使用的是全局变量 window.i。更改您的函数,以便将 i 声明为局部变量:

function constructBuilder() {
var qb_boxes_innerHTML = "";
var i;
/* ... */
}

关于javascript - 为什么这个javascript无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057871/

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