确定Javascript对象是否是“复杂”对象。对象或只是一个字符串 [英] Determining if a Javascript object is a "complex" object or just a string
问题描述
我希望能够传递字符串文字,
I want to be able to pass either a string literal,
'this is a string'
或javascript对象,
or a javascript object,
{one: 'this', two: 'is', three: 'a', four: 'string' }
作为函数的参数,并根据它是字符串还是对象采取不同的操作。我如何确定哪个是真的?
as argument to a function, and take different actions depending on whether it's a string or an object. How do I determine which is true?
具体来说,我想迭代对象的属性,如果属性是字符串,则进行一些解析,但是如果属性是对象,则递归嵌套。我已经想出如何使用 $。each()
来迭代对象的属性,但是如果我只是对字符串执行此操作,它会将字符串视为一系列字母而不是一个单一的东西。我可以通过其他方式解决这个问题吗?
To be specific, I want to iterate over the properties of an object, and do some parsing if a property is a string, but nest recursively if the property is an object. I've figured out how to use $.each()
to iterate over the properties of the object, but if I just do this with the string, it treates the string as an array of letters rather than as a single thing. Can I get around this some other way?
推荐答案
var data = {
foo: "I'm a string literal",
bar: {
content: "I'm within an object"
}
};
jQuery
$.each(data, function(i, element){
if($.isPlainObject(element){
// we got an object here
}
});
有类似的方法,如 jQuery lib中的$ .isArray()
或 $。isFunction()
。
原生Javascript
for(var element in data){
if(toString.call(element) === '[object Object]'){
// we got an object here
}
}
使用 hack'ish
方式与 toString
有一个好处,你可以确定它是真的
一个对象和一个数组
。两者,对象和数组都会使用 typeof元素
返回 object
。
To use the hack'ish
way with toString
has the advantage, that you can identify whether it is really
an object and an array
. Both, objects and arrays would return object
by using typeof element
.
长篇故事简而言之,您不能依赖 typeof
运算符来区分真正的对象
和数组
。为此,您需要 toString.call()
。如果您只是需要知道它是否是任何对象, typeof
就可以了。
Long story short, you cannot rely on the typeof
operator to distinguish true objects
and arrays
. For that you need the toString.call()
. If you just need to know whether it is any object or not, typeof
is just fine.
这篇关于确定Javascript对象是否是“复杂”对象。对象或只是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!