Coffeescript 调用函数并在单行中显式返回?

Coffeescript 调用函数并在单行中显式返回?,coffeescript,Coffeescript,是否可以调用函数并在同一行返回: foo() and return if conditon == true 而不是拆分为多行?尝试时,return突出显示,出现以下错误: error: cannot use a pure statement in an expression return不是CoffeeScript中的表达式,和的形式如下: expr和expr 由于return不是一个表达式,因此在说出expr和return时,必须看到所看到的错误 不过,有多种方法可以解决这个问题,您选择哪

是否可以调用函数并在同一行返回:

foo() and return if conditon == true
而不是拆分为多行?尝试时,
return
突出显示,出现以下错误:

error: cannot use a pure statement in an expression

return
不是CoffeeScript中的表达式,
的形式如下:

exprexpr

由于
return
不是一个表达式,因此在说出
expr和return
时,必须看到所看到的错误

不过,有多种方法可以解决这个问题,您选择哪种方法取决于您希望返回的
foo()
,以及您希望函数返回的内容

如果你不在乎回报什么,那就直接开始吧:

return foo() if(condition)
记住
return
returnundefined
是同一件事

如果
foo()

如果
foo()
返回错误值,则切换到
|
(或
):

如果您不知道
foo()
将返回什么(如果有),那么事情就会变得糟糕。如果CoffeeScript有一个:

逗号运算符计算其两个操作数(从左到右)并返回第二个操作数的值

然后你可以说:

return foo(), undefined if(condition)
这不起作用,因为CoffeeScript没有逗号运算符。但是,您可以使用一个额外的函数来模拟它:

comma = (a, b) -> b
#...
return comma(foo(), undefined) if(condition)
或使用
do
的SIF版本:

return (do -> foo(); return) if(condition)
或者,您可以使用backticks将原始JavaScript嵌入到您的咖啡脚本中:

return `foo(), undefined` if(condition)
或者您可以将
&&
|
技术结合起来:

return (foo() || undefined) && undefined if(condition)
演示:



如果(条件)
信息有限,我倾向于使用
返回foo()。

您是调用函数foo()还是试图定义它。另外,如果您试图调用该函数,foo()将返回什么?字符串、整数、布尔值等?调用它,这就是为什么函数后面有()的原因
foo
返回什么?在我的例子中,foo()不返回任何有意义的内容,可以忽略它。
只是让它更易于阅读的一种方式,感谢您的详细回答。如果可以的话,我会投10票!
return `foo(), undefined` if(condition)
return (foo() || undefined) && undefined if(condition)