Javascript 未捕获的类型错误:无法读取未定义的属性“toString”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27452478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'toString' of undefined
提问by Rehman Khan
Why is my code not working?
Chrome gives me the following error: Uncaught TypeError: Cannot read property 'toString' of undefined.
为什么我的代码不起作用?Chrome 给了我以下错误:Uncaught TypeError: Cannot read property 'toString' of undefined.
It works with 1,2,3,4,6,7,8,9 but does not work with 5,10,15,...
它适用于 1,2,3,4,6,7,8,9 但不适用于 5,10,15,...
Please help me out.
请帮帮我。
Here is my javascript code:
这是我的 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>
Here is my html:
这是我的 html:
<code><input type="text" id="txt" value="" onchange="mmCal(this.value)"></code>
<code><input type="text" id="txtt" value=""></code>
回答by sebnukem
It doesn't work when ais an integer because there's no period to split your string, and that happens with multiples of 5.
当a是整数时它不起作用,因为没有句点来分割你的字符串,而这发生在 5 的倍数。
回答by Wilfredo P
As Sebnukem says
正如塞布努克姆所说
It doesn't work when a is an integer because there's no period to split your string, and that happens with multiples of 5.
当 a 是整数时它不起作用,因为没有句点来分割你的字符串,而这发生在 5 的倍数上。
But you could have a trick so use a % 1 != 0to know wherther the value is a decimal see the code below:
但是你可以有一个技巧,所以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;
}
}
That could you help you.
那可以帮到你。
回答by Ariel
Strange way of rounding a number to an integer :-)
将数字四舍五入为整数的奇怪方法:-)
You are converting inches to millimeters, and then rounding that to an integer, right?
您正在将英寸转换为毫米,然后将其四舍五入为整数,对吗?
Why not use 'toFixed()' on the number? See: Number.prototype.toFixed()
为什么不在数字上使用“toFixed()”?参见:Number.prototype.toFixed()
I mean:
我的意思是:
function mmCal(val) {
var a, rounded;
a = val * 25.4;
rounded = a.toFixed();
document.getElementById("txtt").value = rounded;
}
(you may also use "toFixed(0)" for the explicit precision).
(您也可以使用“toFixed(0)”来获得显式精度)。

