Javascript生成错误数字的问题

Issue With Javascript Generating The Wrong Numbers

本文关键字:问题 数字 错误 Javascript      更新时间:2023-09-26

抱歉标题,这个问题非常特定于我的代码,我不知道如何措辞。

我正在制作一个网页,可用于在给定范围内将里程转换为KM,或将KM转换为里程。我有两个用于输入的文本框,因此例如,如果您输入 5 和 50,它将生成一个表格,其中包含从 5 英里/公里到 50 英里/公里的所有转换,具体取决于选择的转换。

问题是,如果给定范围内的较大数字高于 10 并且低于乘以 10 的数字,则这不起作用。

例如,如果我输入 3 和 10,它只会生成一个包含 10 转换的表,而不是介于两者之间的数字。使用 3 和 9 到 30、99 和 300、999 和 3000 之间的任何数字也是如此。

这是我确定一定是导致问题的代码:

//gets values in the textboxes, used for the range of conversions
var f = document.getElementById(from).value;
var t = document.getElementById(to).value;
//finds which one is lowest and highest, stores them in appropriate variables
if(f > t) {
    max = f;
    min = t;
} else {
    max = t;
    min = f;
}

表生成:

//Loops using the lowest number as a start for the for loop, ending only when it is less than or equal to the highest number
//Makes the table, inserting appropriate conversion numbers
//NOTE: choice is a boolean used to check whether we are converting from Miles to KM or KM to Miles
for(var i = min; i <= max; i++) {
    if(choice) {
        var row = tab.appendChild(document.createElement("tr"));
        for (var j = 0; j < 2; j++) {
            var cell = row.appendChild(document.createElement("td"));
            if(j == 0) {
                cell.appendChild(document.createTextNode(i));
            } else {
                cell.appendChild(document.createTextNode(convertToKm(i)));
            }
        }
    } else {
        var row = tab.appendChild(document.createElement("tr"));
        for (var j = 0; j < 2; j++) {
            var cell = row.appendChild(document.createElement("td"));
            if(j == 0) {
                cell.appendChild(document.createTextNode(i));
            } else {
                cell.appendChild(document.createTextNode(convertToMiles(i)));
            }
        }
    }
}

这让我发疯,我确信这是一个小错误。

问题就在这里:

var f = document.getElementById(from).value;
var t = document.getElementById(to).value;

ft 都将是字符串,因为它们来自输入字段,因此3"大于"例如10。 您需要将它们解析为数字,使用 parseInt

var f = parseInt(document.getElementById(from).value, 10);
var t = parseInt(document.getElementById(to).value, 10);