[英]How to check if variable is String type
我正在使用ajax获取数据,结果可以是结果数组,也可以是“找不到结果”的字符串语句。 我怎么知道我是否有任何结果? 我试过这种方法:
if result == String
do something
但它不起作用,就像
if typeof(result) == "string"
do something
还有其他功能可以帮助我获取变量的类型吗? 或者也许我可以测试它的数组类型,它也会非常有帮助
使用typeof
doSomething(result) if typeof result is 'string'
请注意, typeof
是一个操作符而不是一个函数,所以你不写typeof(result)
你也可以这样做
doSomethingElse(result) if typeof result isnt 'string'
甚至
return if typeof result is 'string'
doSomething result
else
doSomethingElse result
有关Coffeescript
条件的更多信息,请参见http://coffeescript.org/#conditionals 。
这可以通过许多常见库的方式来完成:
isString = (obj) -> toString.call(obj) == '[object String]'
您还可以尝试使用本机Array.isArray
函数,并回退到类似于上面使用的类型检查样式:
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
这有用吗?
if Object.prototype.toString.call(result) == '[object String]'
do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.