有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
你正在寻找isNaN():
console.log(!isNaN(123)); console.log(!isNaN(-1.23)); console.log(!isNaN(5-2)); console.log(!isNaN(0)); console.log(!isNaN(“0”)); console.log(!isNaN(“2”)); console.log(!isNaN(“Hello”)); console.log(!isNaN(“2005/12/12”));
参见JavaScript isNaN()函数在MDN。
其他回答
你正在寻找isNaN():
console.log(!isNaN(123)); console.log(!isNaN(-1.23)); console.log(!isNaN(5-2)); console.log(!isNaN(0)); console.log(!isNaN(“0”)); console.log(!isNaN(“2”)); console.log(!isNaN(“Hello”)); console.log(!isNaN(“2005/12/12”));
参见JavaScript isNaN()函数在MDN。
试试这个,
<script>
var regInteger = /^-?\d+$/;
function isInteger( str ) {
return regInteger.test( str );
}
if(isInteger("1a11")) {
console.log( 'Integer' );
} else {
console.log( 'Non Integer' );
}
</script>
创建了一个jsperf,用于检查变量是否为数字。很有趣!Typeof实际上有一个性能用途。对于数字以外的任何东西使用typeof,通常以速度的1/3作为变量。构造函数,因为javascript中的大多数数据类型都是对象;数字不是!
http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number
Typeof变量=== 'number'|最快|如果你想要一个数字,比如5,而不是'5' typeof parseFloat(variable) === 'number'|最快|如果你想要一个数字,比如5,和'5'
isNaN()比较慢,但也没慢那么多。我对parseInt和parseFloat寄予厚望,但它们的速度慢得可怕。
效率测试
我知道我该怎么用…
isNaN(parseFloat(n)) && !isNaN(n - 0)} 函数isNumberRE (n){返回/ ^ - ? (\ d。)+ (?:e - ? \ d +) ?美元/ test (n);} function test(fn, timerLabel) { console.time (timerLabel) For (i = 0;I < 1000000;我+ +){ const num = Math.random() * 100 const isNum = fn(num) } console.timeEnd (timerLabel) } test(isNumber, "Normal way") test(isNumberRE, "RegEx方式")
Normal way: 25.103271484375 ms
RegEx way: 334.791015625 ms
我发现的同时考虑正数和负数的最好方法是: O'Reilly Javascript和DHTML烹饪书:
function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString( );
for (var i = 0; i < str.length; i++) {
oneChar = str.charAt(i).charCodeAt(0);
// OK for minus sign as first character
if (oneChar = = 45) {
if (i = = 0) {
continue;
} else {
alert("Only the first character may be a minus sign.");
return false;
}
}
// OK for one decimal point
if (oneChar = = 46) {
if (!oneDecimal) {
oneDecimal = true;
continue;
} else {
alert("Only one decimal is allowed in a number.");
return false;
}
}
// characters outside of 0 through 9 not OK
if (oneChar < 48 || oneChar > 57) {
alert("Enter only numbers into the field.");
return false;
}
}
return true;
}