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?
Therefore:
UPDATE:
Some further considerations:
See @Andy E's comment below.
typeof null
returns"object"
as well. The same applies to any other object, including arrays.Try this:
Thanks to Andy E for the tipp with
argument.constructor
.you can do something like this
Try the typeof operator. It will return
object
for objects andstring
for strings.I was having a similar problem and I think I figured out a solution. Here is my sample code for anyone who is interested.
This will go through all the properties of an object — even if the properties are objects themselves — and return a string with the following values in dot syntax.
I got the inspiration from DavidPirek.com — Thanks Mr. Pirek!
jQuery
There are similar methods like
$.isArray()
or$.isFunction()
within the jQuery lib.Native Javascript
To use the
hack'ish
way withtoString
has the advantage, that you can identify whether it isreally
an object and anarray
. Both, objects and arrays would returnobject
by usingtypeof element
.Long story short, you cannot rely on the
typeof
operator to distinguish trueobjects
andarrays
. For that you need thetoString.call()
. If you just need to know whether it is any object or not,typeof
is just fine.