admin管理员组文章数量:1129794
In Java, you can use instanceOf
or getClass()
on a variable to find out its type.
How do I find out a variable's type in JavaScript which isn't strongly-typed?
For example, how do I know if the bar
is a Boolean
or a Number
, or a String
?
function foo(bar) {
// what do I do here?
}
In Java, you can use instanceOf
or getClass()
on a variable to find out its type.
How do I find out a variable's type in JavaScript which isn't strongly-typed?
For example, how do I know if the bar
is a Boolean
or a Number
, or a String
?
function foo(bar) {
// what do I do here?
}
Share
Improve this question
asked Dec 16, 2010 at 0:19
Tom TuckerTom Tucker
11.9k23 gold badges93 silver badges130 bronze badges
1
- see also: stackoverflow.com/questions/24318654 – dreftymac Commented Jun 20, 2014 at 1:47
12 Answers
Reset to default 307Use typeof
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
So you can do:
if(typeof bar === 'number') {
//whatever
}
Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
The type of an array is still object
. Here you really need the instanceof
operator.
Update:
Another interesting way is to examine the output of Object.prototype.toString
:
> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"
With that you would not have to distinguish between primitive values and objects.
typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof
to test if an object is of a specific type.
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
Using type
:
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof always return a string
typeof String("abc") === 'string'; // but never use this form!
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // an undefined variable
// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date() === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1) === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object'; // this is confusing. Don't use!
// Functions
typeof function(){} === 'function';
typeof Math.sin === 'function';
In Javascript you can do that by using the typeof function
console.log(typeof bar);
To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):
In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)
The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.
As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:
function Type(x) {
if (x === null) {
return 'Null';
}
switch (typeof x) {
case 'undefined': return 'Undefined';
case 'boolean' : return 'Boolean';
case 'number' : return 'Number';
case 'string' : return 'String';
default : return 'Object';
}
}
For builtin JS types you can use:
function getTypeName(val) {
return {}.toString.call(val).slice(8, -1);
}
Here we use 'toString' method from 'Object' class which works different than the same method of another types.
Examples:
// Primitives
getTypeName(42); // "Number"
getTypeName("hi"); // "String"
getTypeName(true); // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null); // "Null"
getTypeName(undefined); // "Undefined"
// Non-primitives
getTypeName({}); // "Object"
getTypeName([]); // "Array"
getTypeName(new Date); // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/); // "RegExp"
getTypeName(new Error); // "Error"
If you need a class name you can use:
instance.constructor.name
Examples:
({}).constructor.name // "Object"
[].constructor.name // "Array"
(new Date).constructor.name // "Date"
function MyClass() {}
let my = new MyClass();
my.constructor.name // "MyClass"
But this feature was added in ES2015.
I find it frustrating that typeof
is so limited. Here’s an improved version:
var realtypeof = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
if (obj instanceof Date)
return '[object Date]';
if (obj instanceof RegExp)
return '[object regexp]';
if (obj instanceof String)
return '[object String]';
if (obj instanceof Number)
return '[object Number]';
return 'object';
// object literals
default:
return typeof(obj);
}
};
sample test:
realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
Hopefully a complete one… What's missing?
本文标签: Finding Variable Type in JavaScriptStack Overflow
版权声明:本文标题:Finding Variable Type in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736738988a1950405.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论