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
To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.
Use the isinstance() Function to Check if a Variable Is a String or Not. It is therefore encouraged to use the isinstance() function over the traditional type() . The isinstance() function checks whether an object belongs to the specified subclass.
Using the typeof Operator The typeof operator is used to check the variable type in JavaScript. It returns the type of variable. We will compare the returned value with the “boolean” string, and if it matches, we can say that the variable type is Boolean.
The Java instanceof keyword is used to check if an object is a certain type. It returns true or false. For example, we can check if a variable is a type of String; we can test classes to see if they are certain types (e.g., is a Birch a Tree or a BoysName?).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With