How do you check if a value is an Object in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
The Ramda functional library has a wonderful function for detecting JavaScript types.
Paraphrasing the full function:
I had to laugh when I realized how simple and beautiful the solution was.
Example usage from Ramda documentation:
i found a "new" way to do just this kind of type checking from this SO question: Why does instanceof return false for some literals?
from that, i created a function for type checking as follows:
then you can just do:
this is tested on Chrome 56, Firefox 52, Microsoft Edge 38, Internet Explorer 11, Opera 43
edit:
if you also want to check if a variable is null or undefined, you can use this instead:
update from inanc's comment: challenge accepted :D
if you want to loose compare objects you can try this way:
that way, you can do just like inanc's comment:
or
Let's define "object" in Javascript. According to the MDN docs, every value is either an object or a primitive:
What's a primitive?
3
'abc'
true
null
undefined
What's an object (i.e. not a primitive)?
Object.prototype
Object.prototype
Function.prototype
Object
Function
function C(){}
-- user-defined functionsC.prototype
-- the prototype property of a user-defined function: this is notC
s prototypenew C()
-- "new"-ing a user-defined functionMath
Array.prototype
{"a": 1, "b": 2}
-- objects created using literal notationnew Number(3)
-- wrappers around primitivesObject.create(null)
Object.create(null)
How to check whether a value is an object
instanceof
by itself won't work, because it misses two cases:typeof x === 'object'
won't work, because of false positives (null
) and false negatives (functions):Object.prototype.toString.call
won't work, because of false positives for all of the primitives:So I use:
@Daan's answer also seems to work:
because, according to the MDN docs:
A third way that seems to work (not sure if it's 100%) is to use
Object.getPrototypeOf
which throws an exception if its argument isn't an object:The official underscore.js uses this check to find out if something is really an object
Object.prototype.toString.call(myVar)
will return:"[object Object]"
if myVar is an object"[object Array]"
if myVar is an arrayFor more information on this and why it is a good alternative to typeof, check out this article.
Little late... for "plain objects" (i mean, like {'x': 5, 'y': 7}) i have this little snippet:
It generates the next output:
It always works for me. If will return "true" only if the type of "o" is "object", but no null, or array, or function. :)