有人知道如何在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

其他回答

最好的方法是使用isNaN +类型转换:

更新的all-in方法:

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

使用regex也一样:

function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

------------------------

isNumber('123'); // true  
isNumber('123abc'); // false  
isNumber(5); // true  
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber('   '); // false

聚会很晚才来;然而,当我想一次性检查某些输入是字符串还是数字时,下面的方法总是很有效。

return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);

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

Example: 
   1)  2 ^ 0 = 2
   2)  '2' ^ 0  = 2
   3)  'Str' ^ 0 = 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。

像其他人一样,我沉迷于强类型(即使我喜欢JS)

在我的代码中,我碰巧需要区分数字和字符串,来执行两种截然不同的操作。

而不是高谈阔论:

让int = 123, STR = '123'; console.log (int。构造函数===Number, str.constructor===String);// true true Console.log (typeof int === 'number', typeof STR === 'number');// true false console.log (Number(int)== int, Number(str)===str) // true false //或 console.log (String(int)== int, String(str)===str) // false true //最短的: Console.log (+int== int, +str== str);// true false

因此我主要使用,特别是在三元测试中。

let res = (+X===X) ? stuff_to_do_with_a_Number(X) : stuff_to_do_with_a_String(X);

当然,这必须小心处理。