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


当前回答

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

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

其他回答

像其他人一样,我沉迷于强类型(即使我喜欢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);

当然,这必须小心处理。

//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

//basic usage
is('String', 'test'); // true
is('Array', true); // false

或者调整它以返回未知类型:

function realTypeOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}

//usage
realTypeOf(999); // 'Number'

2012年5月12日更新: Javascript的完整例子:A Better typeof。

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

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(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

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

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

将提醒“对象”。