在Coffeescript中,这些if
和unless
语句可以成为一行代码吗?
# ensure both variables are present
if var1 and var2
# ensure the variables are different
unless var1 is var2
# now do something!
我需要两个变量都存在,两者都不同。
答案 0 :(得分:2)
只需在第一个a is b
中添加if
的补充,Javascript将开始评估左边的表达式(短路),它不会测试a isnt b
,除非他们都定义了
# Your example boils down to this
if a and b and a isnt b
# Do something
# Why not Use a? to check if a is defined
if a? and b? and a isnt b
# Do something