未捕获的类型错误:无法读取未定义的属性“toString”
Uncaught TypeError: Cannot read property 'toString' of undefined
为什么我的代码不起作用?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)"表示显式精度)。
相关文章:
- TypeError:无法读取属性'推'未定义的JavaScript
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 未捕获的类型错误:无法读取属性'删除'的未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- angularjs无法读取未定义的属性then
- 无法读取属性'材料'未定义的Three.js
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- JavaScript承诺-无法读取属性'那么'的未定义
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 角度推入数组给出:TypeError:无法读取属性'推'的未定义
- Javascript未捕获类型错误:无法读取属性'0'的未定义
- jQuery控制台错误:无法读取属性'top'的未定义
- TypeError:无法读取属性'findAll'的未定义
- 无法读取属性'errcap'未定义的jqgrid
- 无法读取未定义的属性“rid”
- 未捕获的类型错误: 无法读取未定义的属性“图像”
- 可以't读取'getHTML'未定义的Liferay CK Editor内容
- 在node.js中未定义读取属性错误