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


当前回答

如果你处理的是文字符号,而不是构造函数,你可以使用typeof:。

typeof "Hello World"; // string
typeof 123;           // number

如果你通过构造函数创建数字和字符串,比如var foo = new String("foo"),你应该记住typeof可能会返回foo的对象。

也许一个更简单的检查类型的方法是利用underscore.js中的方法(带注释的源代码可以在这里找到),

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

这将返回一个布尔值true:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

其他回答

试试这个,

<script>
var regInteger = /^-?\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>

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

创建了一个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寄予厚望,但它们的速度慢得可怕。

Typeof在大多数情况下都很适合我。您可以尝试使用if语句

if(typeof x === 'string' || typeof x === 'number') {
    console.log("Your statement");
}

x是任意变量名

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

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

将提醒“对象”。