确定Javascript对象是“复杂”对象还是仅仅是字符串
我希望能够传递一个字符串文字,
'this is a string'
或者一个javascript对象,
{one: 'this', two: 'is', three: 'a', four: 'string' }
作为函数的参数,并根据它是字符串还是对象采取不同的操作。 我如何确定哪个是真的?
具体来说,我想迭代对象的属性,如果属性是字符串,则进行一些解析,但如果属性是对象,则递归嵌套。 我已经想出如何使用$.each()
来迭代对象的属性,但是如果我只是用字符串做这个,它会将字符串作为一个字母数组而不是一个单独的东西来处理。 我可以通过其他方式解决这个问题吗?
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 } }
在toString
使用hack'ish
方式有一个优点,即可以识别它是否really
是一个对象和一个array
。 对象和数组都将使用typeof element
返回object
。
长话短说,你不能依靠typeof
运算符来区分真实objects
和arrays
。 为此你需要toString.call()
。 如果你只是需要知道它是否是任何对象, typeof
就好了。
var a = 'this is a string'; console.log(typeof a); // Displays: "string" var b = {one: 'this', two: 'is', three: 'a', four: 'string' }; console.log(typeof b); // Displays: "object"
因此:
if (typeof yourArgument === 'string') { // Do the string parsing } else if (typeof yourArgument === 'object') { // Do the property enumeration } else { // Throw exception }
更新:
进一步考虑:
-
请参阅下面的@Andy E的评论。
-
typeof null
返回"object"
。 这同样适用于任何其他对象,包括数组。
试试这个:
function some_function(argument) { if (typeof(argument) == "string" || argument.constructor == String) { // it's a string literal } else if (argument && typeof(argument) == "object" && argument.constructor != Array) { // it's an object and not null } else { // error } }
感谢Andy E与argument.constructor
的tipp。
尝试使用typeof运算符。 它将返回object
的对象和string
的字符串。
你可以做这样的事情
function something(variableX){ if (typeof(variableX) === 'object'){ // Do something }else if (typeof(variableX) === 'string'){ // Do something } }
我遇到了类似的问题,我想我找到了解决方案。 以下是我感兴趣的任何人的示例代码。
var propToDotSyntax = function (obj) { var parse = function (o, n) { var a = [], t; for (var p in o) { if (o.hasOwnProperty(p)) { t = o[p]; if (n !== undefined) tmp = n + '.' + p; else tmp = p; if (t && typeof(t) === 'object') a.push(arguments.callee(t, tmp)); else a.push(tmp + '=' + t); } } return a; }; return parse(obj).toString(); } var i = { prop: 'string', obj: { subprop: 'substring', subobj: { subsubprop: 'subsubstring' } } }; propToDotSyntax(i);
这将遍历对象的所有属性 – 即使属性本身就是对象 – 并返回带有以下点值语法的值的字符串。
"prop=string,obj.subprop=substring,obj.subobj.subsubprop=subsubstring"
我从DavidPirek.com获得灵感 – 谢谢Pirek先生!