[英]Can anyone tell me why I get a error when i try to call this function?
<!doctype html>
<html>
<script>
function isNumber(value) {
return typeof (value) != "boolean" && !isNaN(value) && value.length > 0;
}
function minMaxDefrost(value, min, max) {
if (value.length == 0 || value == "-") return value;
if (!isNumber(value)) return value.substring(0, value.length - 1);
console.log("minMaxDefrost called ")
if (parseFloat(value) < min){
return min;
}
else if (parseFloat(value) > max){
return max;
}
else {
return Math.floor(value);
}
}
minMaxDefrost(4, 0, 12);
</script>
</html>
isNumber(4)
evaluates to false
, so you're trying to call a substring
method on 4
but that doesn't exist. isNumber(4)
计算结果为false
,因此您尝试在4
上调用substring
方法,但该方法不存在。 Use typeof value === 'number'
instead to test if something is a number.使用
typeof value === 'number'
来测试某个东西是否是数字。 Or better yet, use typeof value === 'string'
before treating it like it's definitely a string.或者更好的是,在将它视为绝对是字符串之前使用
typeof value === 'string'
。
isNumber
doesn't exactly do its job as Mark Hanna suggests.. a better isNumber
would be something like isNumber
并没有像 Mark Hanna 建议的那样完全完成它的工作......更好的isNumber
应该是这样的
function isNumber(num){
let num1=num-0, num2=num-1
return num2!=num1 && !!(num2||num1) && typeof(num)!="object"
//Infinity would fail the test num2!=num1
//Normal non-numbers would fail !!(num2||num1)
//null would fail typeof(null)!="object"
//However, 0, and even "0" will pass this test
}
Here is it returned in the code you gave us这是您提供给我们的代码中返回的
function isNumber(num){ let num1=num-0, num2=num-1 return num2!=num1 && !!(num2||num1) && typeof(num)!="object" //Infinity would fail the test num2!=num1 //Normal non-numbers would fail !!(num2||num1) //null would fail typeof(null)!="object" //However, 0, and even "0" will pass this test } function minMaxDefrost(value, min, max) { if (value.length == 0 || value == "-") return value; if (!isNumber(value)) return value.substring(0, value.length - 1); console.log("minMaxDefrost called ") if (parseFloat(value) < min){ return min; } else if (parseFloat(value) > max){ return max; } else { return Math.floor(value); } } minMaxDefrost(4, 0, 12);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.