Jai*_*der 89 undefined coffeescript
在javascript中检查变量是否从未创建过,我们就这么做了
if (typeof MyVariable !== "undefined"){ ... }
Run Code Online (Sandbox Code Playgroud)
我很想知道我是如何在coffeescript中做到的?...我尝试了类似的东西
if (MyVariable?false){ ... }
Run Code Online (Sandbox Code Playgroud)
但是这检查if是否MyVariable
是一个函数,如果是这样,将调用MyVariable(false),如果不是,那将调用void(0)或类似的东西.
Jai*_*der 163
最后我找到了这个简单的方法:
if (MyVariable?){ ... }
Run Code Online (Sandbox Code Playgroud)
这会产生:
if (typeof MyVariable !== "undefined" && MyVariable !== null){ ... }
Run Code Online (Sandbox Code Playgroud)
更新04/07/2014 演示链接
小智 26
首先,回答你的问题:
if typeof myVariable isnt 'undefined' then # do stuff
Run Code Online (Sandbox Code Playgroud)
Magrangs的解决方案在大多数情况下都有效,除非你需要区分undefined和false(例如,如果myVariable可以是true,false或undefined).
只是要指出,你不应该把你的条件包括在括号中,你不应该使用花括号.
then
如果所有内容都在同一行,则可以使用该关键字,否则使用缩进来指示条件内的代码.
if something
# this is inside the if-statement
# this is back outside of the if-statement
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
AJP*_*AJP 14
这个答案适用于较旧版本的coffeescript.如果您想获得更新的答案,请参阅上面的Jaider答案(截至2014年7月)
这个coffeescript做你想要的我想:
if not MyVariable?
MyVariable = "assign a value"
Run Code Online (Sandbox Code Playgroud)
哪个产生:
if (!(typeof MyVariable !== "undefined" && MyVariable !== null)) {
MyVariable = "assign a value";
}
Run Code Online (Sandbox Code Playgroud)
Nb,如果你首先进行赋值MyVariable
,即使你MyVariable
在此代码中设置为undefined ,那么这将编译为:
if (!(MyVariable != null)) {
MyVariable = "assign a value";
}
Run Code Online (Sandbox Code Playgroud)
我相信这是有效的,因为!=
CoffeeScripts Existential Operator
(问号)使用的强制undefined
等于null
.
ps你真的能if (MyVariable?false){ ... }
上班吗?除非在存在运算符和false之间存在空格,否则它不会为我编译,MyVariable? false
这会使CoffeeScript将其检查为函数,因为false
它认为它是您的参数MyVariable
,例如:
if MyVariable? false
alert "Would have attempted to call MyVariable as a function"
else
alert "but didn't call MyVariable as it wasn't a function"
Run Code Online (Sandbox Code Playgroud)
生产:
if (typeof MyVariable === "function" ? MyVariable(false) : void 0) {
alert("Would have attempted to call MyVariable as a function");
} else {
alert("but didn't call MyVariable as it wasn't a function");
}
Run Code Online (Sandbox Code Playgroud)
小智 9
除了Jaider上面给出的答案(由于声誉不足我无法发表评论),请注意,如果它是对象/数组中的某个内容,则它是一个不同的情况:
someArray['key']?
Run Code Online (Sandbox Code Playgroud)
将被转换为:
someArray['key'] != null
Run Code Online (Sandbox Code Playgroud)
js2coffee.org的屏幕截图:
我只是用:
if (myVariable)
//do stuff
Run Code Online (Sandbox Code Playgroud)
因为undefined是假的,所以如果myVariable没有未定义,它只会做东西.
你只需要知道它将为0,""和null的值"做东西"