简体   繁体   English

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

[英]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". 我正在使用ajax获取数据,结果可以是结果数组,也可以是“找不到结果”的字符串语句。 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 使用typeof

doSomething(result) if typeof result is 'string'

Note that typeof is an operator not a function so you don't write typeof(result) 请注意, typeof是一个操作符而不是一个函数,所以你不写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. 有关Coffeescript条件的更多信息,请参见http://coffeescript.org/#conditionals

Check that the result is a String: 检查结果是否为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: 您还可以尝试使用本机Array.isArray函数,并回退到类似于上面使用的类型检查样式:

isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'

Does this work? 这有用吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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