gpt4 book ai didi

javascript - For 循环会卡住 Javascript?

转载 作者:行者123 更新时间:2023-11-30 10:38:47 26 4
gpt4 key购买 nike

这是我的 web 编程类(class)的一个小外部 js 脚本,它应该提示用户为员工工作的小时数,直到他们输入负数,当它打印一个具有适当行数的表(数字已为其输入工时的员工的数量),其中包含一个工作时间列和一个工资列。但是最后关于 for 循环的事情是卡住了我浏览器中的 js 引擎。如果我评论循环,提示工作正常。如果我输入一个无意义的 while 循环,它会在屏幕上打印一些东西,提示仍然有效,然后 while 循环运行。但是这个愚蠢的 for 循环只是卡住了整个脚本,而打开 HTML 页面实际上什么也没做。空白页。作业已经迟到了,我束手无策。

var empHours = 0;
var numEmployees = 0;
var empWage = 0;
var totalWages = 0;
var empWages = new Array();

do {
empHours = prompt("Enter number of hours employee worked this week.");

if (empHours > -1) {
numEmployees++;
if (empHours <= 40) {
empWage = (15 * empHours)
empWages[numEmployees-1] = empWage;
totalWages += empWage;
} else {
empWage = (15 * 1.5 * empHours);
empWages[numEmployees-1] = (15 * 1.5 * empHours);
totalWages += empWage;
}
}
} while (empHours > -1);

confirm("You have " + numEmployees + " employees, is this correct?");

var root = document.getElementById('tablediv');
var table = document.createElement('table');
var row, cell;

for (i=0; i<=numEmployees; i++) {
document.write("Made it to for loop"):
row = table.insertRow(i);
for (j=0; j<3; j++) {
cell = row.insertCell(j);
cell.innerHTML(empWages[i])
}
}
root.appendChild(table);

最佳答案

提示返回空值或字符串。它不返回数字。

我建议你改成:

while (empHours && parseInt(empHours, 10) >= 0)

这可以防止 null 并在检查它是否为负数之前将字符串转换为数字。

此外,我建议您永远不要使用 document.write() 进行调试。如果在错误的时间使用,它真的会搞乱现有的页面。您应该使用 console.log() 或实际的调试器。

关于javascript - For 循环会卡住 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399340/

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