1

这是我的网络编程课的一个小外部 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);
4

2 回答 2

1

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

我建议您更改为:

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

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

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

于 2012-09-13T04:22:13.300 回答
1

您的问题似乎是语法错误,错字。

document.write("Made it to for loop"):
                                     ^
                                this is the problem in your for loop.

您上面的测试实际上也在删除表。删除document.write,您的代码工作正常。

演示

于 2012-09-13T04:27:02.423 回答