I want to be able to pass either a string literal,
'this is a string'
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?
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?
jQuery
There are similar methods like
$.isArray()or$.isFunction()within the jQuery lib.Native Javascript
To use the
hack'ishway withtoStringhas the advantage, that you can identify whether it isreallyan object and anarray. Both, objects and arrays would returnobjectby usingtypeof element.Long story short, you cannot rely on the
typeofoperator to distinguish trueobjectsandarrays. For that you need thetoString.call(). If you just need to know whether it is any object or not,typeofis just fine.