有人知道如何在JavaScript中检查变量是数字还是字符串吗?


当前回答

效率测试

我知道我该怎么用…

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

其他回答

这个解决方案解决了这里提出的许多问题!

这是迄今为止我用过的最可靠的方法。这不是我发明的,也不记得我最初是在哪里找到它的。但它在其他技术失败的地方奏效:

// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
  if (undefined === data ){ return 'Undefined'; }
  if (data === null ){ return 'Null'; }
  return {}.toString.call(data).slice(8, -1);
};  
// End public utility /getVarType/

正确性的例子

var str = new String();
console.warn( getVarType(str) ); // Reports "String"    
console.warn( typeof str );      // Reports "object"

var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num );      // Reports "object"

var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list );        // Reports "object"

异或操作可用于检测数字或字符串。 Number ^ 0将始终以相同的数字作为输出,而string ^ 0将以0作为输出。

Example: 
   1)  2 ^ 0 = 2
   2)  '2' ^ 0  = 2
   3)  'Str' ^ 0 = 0

下面是一种基于通过添加零或空字符串将输入强制为数字或字符串的方法,然后进行类型化的相等比较。

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); }

你正在寻找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。

我发现的最好的方法是检查字符串上的方法,即:

if (x.substring) {
// do string thing
} else{
// do other thing
}

或者如果你想对number属性做一些检查,

if (x.toFixed) {
// do number thing
} else {
// do other thing
}

这有点像“鸭子打字”,由你自己决定哪种方式最有意义。我没有足够的因果报应来评论,但typeof失败的盒装字符串和数字,即:

alert(typeof new String('Hello World'));
alert(typeof new Number(5));

将提醒“对象”。