Tom*_*han 7 javascript string jquery object
我希望能够传递一个字符串文字,
'this is a string'
Run Code Online (Sandbox Code Playgroud)
或者是一个javascript对象,
{one: 'this', two: 'is', three: 'a', four: 'string' }
Run Code Online (Sandbox Code Playgroud)
作为函数的参数,并根据它是字符串还是对象采取不同的操作.我如何确定哪个是真的?
具体来说,我想迭代对象的属性,如果属性是字符串,则进行一些解析,但如果属性是对象,则递归嵌套.我已经弄清楚如何使用$.each()迭代对象的属性,但如果我只是用字符串做这个,它会将字符串作为一个字母数组而不是一个单独的东西来处理.我可以通过其他方式解决这个问题吗?
var data = {
foo: "I'm a string literal",
bar: {
content: "I'm within an object"
}
};
Run Code Online (Sandbox Code Playgroud)
jQuery的
$.each(data, function(i, element){
if($.isPlainObject(element){
// we got an object here
}
});
Run Code Online (Sandbox Code Playgroud)
jQuery lib中有类似$.isArray()或类似的方法$.isFunction().
原生Javascript
for(var element in data){
if(toString.call(element) === '[object Object]'){
// we got an object here
}
}
Run Code Online (Sandbox Code Playgroud)
使用hack'ish方式toString有优势,你可以识别它是really一个对象和一个array.对象和数组都将object通过使用返回typeof element.
长话短说,你不能依靠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"
Run Code Online (Sandbox Code Playgroud)
因此:
if (typeof yourArgument === 'string') {
// Do the string parsing
}
else if (typeof yourArgument === 'object') {
// Do the property enumeration
}
else {
// Throw exception
}
Run Code Online (Sandbox Code Playgroud)
更新:
进一步考虑:
请参阅下面的@Andy E的评论.
typeof null也回来"object"了.这同样适用于任何其他对象,包括数组.