检查变量是否为JavaScript中的数字或字符串 [英] Check whether variable is number or string in JavaScript
问题描述
有谁知道如何检查变量是JavaScript中的数字还是字符串?
Does anyone know how can I check whether a variable is a number or a string in JavaScript?
推荐答案
如果你'重新处理文字符号,而不是构造函数,您可以使用 typeof :。
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
如果您是通过构造函数创建数字和字符串,例如 var foo = new String(foo)
,你应该记住 typeof
可能会返回 object
for foo
。
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.
或许更简单的检查类型的方法是利用 underscore.js (可在此处找到带注释的来源。 ),
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
返回布尔值 true
对于以下内容:
This returns a boolean true
for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
这篇关于检查变量是否为JavaScript中的数字或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!