有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
或者只使用isNaN()的倒数:
if(!isNaN(data))
do something with the number
else
it is a string
是的,使用jQuery的$. isnumeric()更有趣。
其他回答
我发现的同时考虑正数和负数的最好方法是: 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;
}
自ES2015以来,检查变量的正确方法 是number . isfinite (value)
例子:
Number.isFinite(Infinity) // false
Number.isFinite(NaN) // false
Number.isFinite(-Infinity) // false
Number.isFinite(0) // true
Number.isFinite(2e64) // true
Number.isFinite('0') // false
Number.isFinite(null) // false
下面是一种基于通过添加零或空字符串将输入强制为数字或字符串的方法,然后进行类型化的相等比较。
function is_number(x) { return x === x+0; }
function is_string(x) { return x === x+""; }
由于一些无法理解的原因,x===x+0似乎比x===+x执行得更好。
有没有失败的情况?
同样地:
function is_boolean(x) { return x === !!x; }
这似乎比x===true || x===false或typeof x==="boolean"稍微快(并且比x=== boolean (x)快得多)。
然后还有
function is_regexp(x) { return x === RegExp(x); }
所有这些都依赖于特定于每种类型的“标识”操作的存在,该操作可以应用于任何值,并可靠地产生有关类型的值。我想不出这样的操作日期。
对于NaN来说,有
function is_nan(x) { return x !== x;}
这基本上是下划线的版本,它的速度大约是isNaN()的四倍,但下划线源代码中的注释提到“NaN是唯一不等于自身的数字”,并添加了_.isNumber检查。为什么?还有什么物体不与它们相等呢?同样,下划线使用x !== +x——但是这里的+有什么区别呢?
对于偏执狂来说:
function is_undefined(x) { return x===[][0]; }
或者这个
function is_undefined(x) { return x===void(0); }
能把它除以1吗?
我假设问题将是一个字符串输入,如:"123ABG"
var Check = "123ABG"
if(Check == Check / 1)
{
alert("This IS a number \n")
}
else
{
alert("This is NOT a number \n")
}
我最近就是这么做的。
你正在寻找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。