coffeescript - 如何在 Coffeescript 中正确格式化长复合 if 语句

标签 coffeescript

如果我有一个复杂的 if 语句,我不想​​仅仅出于美观目的而溢出,那么分解它的最合理的方法是什么,因为在这种情况下,coffeescript 会将 return 解释为语句的主体?

if (foo is bar.data.stuff and foo isnt bar.data.otherstuff) or (not foo and not bar)
  awesome sauce
else lame sauce

最佳答案

如果该行以运算符结尾,CoffeeScript 不会将下一行解释为语句的主体,所以这是可以的:

# OK!
if a and
not 
b
  c()

它编译为

if (a && !b) {
  c();
}

所以你的if可以被格式化为

# OK!
if (foo is 
bar.data.stuff and 
foo isnt bar.data.otherstuff) or 
(not foo and not bar)
  awesome sauce
else lame sauce

或任何其他换行方案,只要行以 andoris==< 结尾not 或某些此类运算符

至于缩进,您可以缩进 if 的非第一行,只要正文进一步缩进即可:

# OK!
if (foo is 
  bar.data.stuff and 
  foo isnt bar.data.otherstuff) or 
  (not foo and not bar)
    awesome sauce
else lame sauce

你不能做的是:

# BAD
if (foo  #doesn't end on operator!
  is bar.data.stuff and 
  foo isnt bar.data.otherstuff) or 
  (not foo and not bar)
    awesome sauce
else lame sauce

关于coffeescript - 如何在 Coffeescript 中正确格式化长复合 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6626362/

相关文章:

node.js - 调试 mocha 测试的阻力最小的途径是什么?

node.js - CoffeeScript cakefile 任务未完成

javascript - 使用 CoffeeScript 调用 jQuery 库

coffeescript - 如何在 CoffeeScript 中缩进列表理解?

node.js - 在 NodeJS 中观察流式 HTTP 响应进度,express

javascript - jQuery.ajax *仅*检索状态代码但不检索/下载整个文档?

python - Coffeescript 习语相当于 Python 的 for/else?

javascript - jQuery 加载后不运行 "if"

node.js - 无法在 Ubuntu 12.04 上使用 CoffeeScript 安装 Node.js

javascript - 如何对 Mongoose 中的内部数组和匹配元素进行排序