在 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
可能为 foo
返回 object
.
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屋!