Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  146] [ 4]  / answers: 1 / hits: 163048  / 13 Years ago, thu, january 12, 2012, 12:00:00

Is there any way to efficiently check if the variable is Object or Array, in NodeJS & V8?



I'm writing a Model for MongoDB and NodeJS, and to traverse the object tree I need to know if the object is simple (Number, String, ...) or composite (Hash, Array).



It seems that V8 has fast built-in Array.isArray, but how to check if object is an Object? I mean complex object like hash {} or instance of class, not something like new String()?



Usually it may be done as this:



Object.prototype.toString.call(object) == [object Object]


or this:



object === Object(object)


But it seems that this operations aren't cheap, maybe there's some more efficient? It's ok if it's not universal and doesn't works on all engines, I need it only to work on V8.


More From » node.js

 Answers
14

All objects are instances of at least one class – Object – in ECMAScript. You can only differentiate between instances of built-in classes and normal objects using Object#toString. They all have the same level of complexity, for instance, whether they are created using {} or the new operator.



Object.prototype.toString.call(object) is your best bet to differentiate between normal objects and instances of other built-in classes, as object === Object(object) doesn't work here. However, I can't see a reason why you would need to do what you're doing, so perhaps if you share the use case I can offer a little more help.


[#88059] Wednesday, January 11, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;