Reputation: 2103
I'm getting data with ajax, and the result can be either array of results or a string statement like "no results found". How can i tell whether i got any results or not? i tried this approach:
if result == String
do something
but its not working, just like
if typeof(result) == "string"
do something
Is there any other function that can help me get the type of the variable? Or maybe i can test it for Array type, it would also be very helpful
Upvotes: 20
Views: 18782
Reputation: 13486
use typeof
doSomething(result) if typeof result is 'string'
Note that typeof
is an operator not a function so you don't write typeof(result)
You can also do this
doSomethingElse(result) if typeof result isnt 'string'
or even
return if typeof result is 'string'
doSomething result
else
doSomethingElse result
See http://coffeescript.org/#conditionals for more on Coffeescript
conditionals.
Upvotes: 33
Reputation: 320
Does this work?
if Object.prototype.toString.call(result) == '[object String]'
do something
Upvotes: 0
Reputation: 5515
This can be done in the way that many common libraries do it:
isString = (obj) -> toString.call(obj) == '[object String]'
You can also try to use the native Array.isArray
function, and fall back to
a similar style of type checking as used above:
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
Upvotes: 2