在javascript中,要检查变量是否从未创建过,我们只需执行
if (typeof MyVariable !== "undefined"){ ... }
我想知道我如何在coffeescript中做到这一点?我尝试像这样的东西
if (MyVariable?false){ ... }
但是这个检查MyVariable
是否是一个函数,如果是,它将调用MyVariable(false),如果不是,它将调用MyVariable(0)或类似的函数。
发布于 2012-03-30 00:31:48
首先,回答你的问题:
if typeof myVariable isnt 'undefined' then # do stuff
Magrangs的解决方案在大多数情况下都可以工作,除非您需要区分未定义和错误(例如,如果myVariable可以是真、假或未定义)。
需要指出的是,您不应该将条件括在圆括号中,也不应该使用大括号。
如果所有内容都在同一行上,则可以使用then
关键字,否则使用缩进来指示条件中的代码。
if something
# this is inside the if-statement
# this is back outside of the if-statement
希望这能有所帮助!
发布于 2012-03-30 00:25:34
typeof MyVariable isnt "undefined"
发布于 2012-03-30 00:19:45
我只是使用:
if (myVariable)
//do stuff
因为undefined是错误的,所以只有当myVariable不是undefined时,它才会做一些事情。
您只需知道它将对值为0、"“和null的值”执行操作“
https://stackoverflow.com/questions/9929306
复制相似问题