简体   繁体   中英

How to check if variable is String type

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

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.

Check that the result is a String:

This can be done in the way that many common libraries do it:

isString = (obj) -> toString.call(obj) == '[object String]'

Check that the result is an Array:

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]'

Does this work?

if Object.prototype.toString.call(result) == '[object String]'
    do something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM