我想使用java脚本为范围验证器定义一个函数。我定义了它,但它只适用于整数。我的问题是,最小值和最大值可以是什么?如果最小值和最大值是字符串或其他类型,如何检查它们
这是我的功能:
function minmax(value) {
var min = document.getElementById("min_val").value;
var max = document.getElementById("max_val").value;
if (min <= max) {
if (parseInt(value) < min || isNaN(value)) {
alert("input shouldn't less than " + min);
}
else if (parseInt(value) > max) {
alert("input shouldn't more than " + max);
}
}
else
alert("The MaximumValue cannot be less than the MinimumValue of RangeValidator");
}
普通的旧JavaScript使用typeof
运算符来确定变量或值的底层类型,并返回该类型的字符串值,如下所示:
typeof 37 would return 'number'
typeof 3.14 would return 'number'
typeof "37" would return 'string'
typeof "" would return 'string'
typeof function() {} would return 'function'
typeof true would return 'boolean'
typeof false woulld return 'boolean'
typeof undefined would return 'undefined'
typeof {1, 2, 3} would return 'object'
typeof null would return 'object'
我认为您应该关心的仅有两种类型是'number'
和'string'
,因为您可以将'string'
强制为'number'
。
我会在函数的顶部进行检查,看看min
和max
是否都是'number'
或'string'
,如果不是,则退出函数。