如何检查变量是否为String类型

Leo*_*Leo 19 coffeescript

我正在使用ajax获取数据,结果可以是结果数组,也可以是"找不到结果"的字符串语句.我怎么知道我是否有任何结果?我试过这种方法:

if result == String
    do something
Run Code Online (Sandbox Code Playgroud)

但它不起作用,就像

if typeof(result) == "string"
    do something
Run Code Online (Sandbox Code Playgroud)

还有其他功能可以帮助我获取变量的类型吗?或者也许我可以测试它的数组类型,它也会非常有帮助

Dav*_*Sag 31

使用 typeof

doSomething(result) if typeof result is 'string'
Run Code Online (Sandbox Code Playgroud)

请注意,这typeof是一个操作符而不是一个函数,所以你不写typeof(result)

你也可以这样做

doSomethingElse(result) if typeof result isnt 'string'
Run Code Online (Sandbox Code Playgroud)

甚至

return if typeof result is 'string'
   doSomething result
else
   doSomethingElse result
Run Code Online (Sandbox Code Playgroud)

有关条件的更多信息,请参见http://coffeescript.org/#conditionalsCoffeescript.


phe*_*nal 2

检查结果是否是一个字符串:

这可以通过许多常见库的方式来完成:

isString = (obj) -> toString.call(obj) == '[object String]'
Run Code Online (Sandbox Code Playgroud)

检查结果是否是一个数组:

您还可以尝试使用本机Array.isArray函数,并回退到与上面使用的类似类型检查的风格:

isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
Run Code Online (Sandbox Code Playgroud)