如何有效地检查变量是否是数组或对象(在NodeJS& V8中)? [英] How to efficiently check if variable is Array or Object (in NodeJS & V8)?

查看:333
本文介绍了如何有效地检查变量是否是数组或对象(在NodeJS& V8中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法有效地检查变量是Object还是Array,在NodeJS& V8?

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

我正在为MongoDB和NodeJS编写一个Model,并遍历对象树,我需要知道对象是否简单(Number,String,...)或复合(哈希,数组)。

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).

V8似乎有快速内置的 Array.isArray ,但是如何检查对象是否是对象?我的意思是复杂的对象,比如hash {} 或类的实例,而不是像 new String()

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()?

通常可以这样做:

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

或者:

object === Object(object)

但似乎这个操作并不便宜,也许有一些更有效率?如果它不是通用的并且不适用于所有引擎,那就没关系了,我只需要在V8上工作。

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.

推荐答案

全部对象是至少一个类的实例 - 对象 - 在ECMAScript中。您只能使用 Object#toString 来区分内置类和普通对象的实例。它们都具有相同的复杂程度,例如,它们是使用 {} 还是 new 运算符创建的。

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)是区分正常对象和实例的最佳选择其他内置类,因为 object === Object(object)在这里不起作用。但是,我看不出你为什么需要做你正在做的事情的原因,所以如果你分享用例,我可以提供更多的帮助。

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.

这篇关于如何有效地检查变量是否是数组或对象(在NodeJS& V8中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆