如何让 JS 将输入的数字识别为一个数字?

How Can I make JS recognize my number from input as one number?

如果我输入我的输入,例如 15,它会将其读取为 1 和 5。我如何更改它以便 javascript 不会像两个不同的值一样读取它?

function generate() {
                var x = document.forms["form"]["firstInput"].value;
                var y = document.forms["form"]["secondInput"].value;
                if (isNaN(x) || isNaN(y)) {
                    document.getElementById("errorf").innerHTML =
                        "Input has to be a number!";
                    document.getElementById("wynikf").innerHTML = "";
                } else if (x > y) {
                    document.getElementById("wynikf").innerHTML =
                        "First value can't be lower than second value";
                } else if (x == null || x == "" || y == null || y == "") {
                    document.getElementById("errorf").innerHTML =
                        "Input can't be empty!";
                    document.getElementById("wynikf").innerHTML = "";
                } else {
                    for (var counter = x; counter <= y; counter++) {
                        document.getElementById("result").innerHTML +=
                            counter + "\n";
                    }
                }
            }

您需要先将该值转换为数字,然后再检查是否大于或小于。

无需将字符串转换为数字,您只是按字母顺序对它们进行排序

例如:

"15" > "3" // false because '1' comes before '3'
15 > 3 // true because the number 15 is greater than 3

使用 Number(value) 将值转换为数字。

function generate() {
    var x = Number(document.forms["form"]["firstInput"].value);
    var y = Number(document.forms["form"]["secondInput"].value);
    if (isNaN(x) || isNaN(y)) {
        document.getElementById("errorf").innerHTML =
            "Input has to be a number!";
        document.getElementById("wynikf").innerHTML = "";
    } else if (x > y) {
        document.getElementById("wynikf").innerHTML =
            "First value can't be lower than second value";
    } else {
        for (var counter = x; counter <= y; counter++) {
            document.getElementById("result").innerHTML +=
                counter + "\n";
        }
    }
}