Coffeescript - 减少存在和非相同的代码行?

时间:2015-01-17 12:17:10

标签: javascript coffeescript

在Coffeescript中,这些ifunless语句可以成为一行代码吗?

# ensure both variables are present
if var1 and var2
    # ensure the variables are different
    unless var1 is var2
        # now do something!

我需要两个变量都存在,两者都不同。

1 个答案:

答案 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