我有一个type = number的元素(x)。在我的工作中,在执行数学运算之前验证它的值是一个数字我得出结论,“数字”类型的元素,虽然具有内置验证和有用的输入控件,仍然将其值分配为文本,并且在执行之前需要转换为数字数学运算。我的问题 - 我的代码是真的还是有问题?这是我的工作。输入数字6.
x = document.createElement("input");
x.type = "number";
x.step = "0.1";
x.min = "0";
x.max = "9999";
x.defaultValue = "1";
var p = document.getElementById(x.id).value;
isThisNumber(p);
function isThisNumber(z) {
alert(typeof z + " --- " + typeof (z)); // returns "string --- string"
if (z.isNaN) {
alert("it's not number");
} else {
alert("it's a number"); // returns false - it's a number
}
if (z.toFixed) {
alert("it's a number");
} else {
alert("it's not a number"); // returns false - it's not a number
}
var a = z + z;
alert("sum is : " + a); // returns "66"
var b = Number(z);
var b2 = b + b;
alert("sum is : " + b2); // returns "12"
}
价: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number