如何判断一个javascript对象是简单对象还是复杂对象?
基本上我需要区分以下两个:
var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}
Basically I need to tell apart the following two:
var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
typeof
运算符,您可以确定以下内容:已编辑:
正如评论中所建议的,您可能还想检查 value 是否为 null,因为
typeof null
将返回对象。Using
typeof
operator you can determine the following:Edited:
As it was suggested in a comment you may want to also check if value is null, as
typeof null
will return object.您可以使用
typeof
:基本上:
注意:
null
将返回"object"
,因此您需要检查它。You could use
typeof
:Basically:
Note:
null
will return"object"
, so you need to check for it.问题是不仅仅是 {} 返回“对象”类型
但是,通过使用 toString 您可以进一步检查:
因此,最好的检查方法是:
希望有帮助
The problem is that more than just {} returns a type of 'object'
But, by using toString you can check further:
So, the best way to check is:
Hope that helps
在此注明
Credit here
尝试以下操作
Try the following
就您的情况而言:
据我从您的问题中了解到的,您需要判断该对象是否具有属性/方法。
In your case:
As of what I understand from you question - you need to tell if the object has properties/methods.
您可以创建一个简单的函数,为简单类型返回 true:
请注意,这将为
NaN
返回 true,因为它被视为数字,而为“未定义”返回 false - 但您可以轻松修改它以适应你的具体情况。运行下面的代码片段以查看其实际效果
You could just make a simple function that returns true for simple types:
Note that this will return true for
NaN
as it's considered a number, and false for 'undefined' - but you could easily modify this to suit your specific case.Run the snippet below to see it in action