未捕获的类型错误:无法读取未定义的属性“toString”

Uncaught TypeError: Cannot read property 'toString' of undefined

本文关键字:未定义 读取 属性 toString 类型 错误      更新时间:2023-09-26

为什么我的代码不起作用?Chrome 给我以下错误:Uncaught TypeError: Cannot read property 'toString' of undefined .

它适用于 1,2,3,4,6,7,8,9,但不适用于 5,10,15,...

请帮帮我。

这是我的javascript代码:

<code><script>
function mmCal(val) {
    var a, b, c, d, e, f, g, h, i;
    a = val * 25.4;
    b = a.toString().split(".")[0];
    c = a.toString().split(".")[1];
    d = c.toString().substr(0, 1);
    e = +b + +1;
    f = b;
    if (d>5) {
        document.getElementById("txtt").value = e;
    } else {
        document.getElementById("txtt").value = f;
    }
}
</script></code>

这是我的网页:

<code><input type="text" id="txt" value="" onchange="mmCal(this.value)"></code>
<code><input type="text" id="txtt" value=""></code>

正如Sebnukem所说

当 a 是整数时它不起作用,因为没有句点 拆分字符串,这发生在 5 的倍数上。

但是你可能有一个技巧,所以使用a % 1 != 0知道值是小数,请参阅下面的代码:

function mmCal(val) {
var a, b, c, d, e, f, g, h, i;
a = val * 25.4;
    if(a % 1 != 0){
    b = a.toString().split(".")[0];
    c = a.toString().split(".")[1];
    }
    else{
    b = a.toString();
    c = a.toString();
    }
d = c.toString().substr(0, 1);
e = +b + +1;
f = b;
if (d>5) {
document.getElementById("txtt").value = e;
} else {
document.getElementById("txtt").value = f;
}
}

那你能帮你吗?

现场演示

a 是整数时它不起作用,因为没有句点来拆分字符串,而这种情况发生在 5 的倍数上。

数字四舍五入为整数的奇怪方式:-)

您正在将英寸转换为毫米,然后将其四舍五入为整数,对吗?

为什么不在号码上使用'toFixed()'?参见: Number.prototype.toFixed()

我的意思是:

function mmCal(val) {
    var a, rounded;
    a = val * 25.4;
    rounded = a.toFixed();
    document.getElementById("txtt").value = rounded;
}

(您也可以使用"toFixed(0)"表示显式精度)。