CoffeeScript多行字符串编译为多行字符串。

50

这个字符串为什么会出现呢

"answer 
 to life 
 the universe 
 and everything
 is
 #{40+2}
"

编译成

"  answer   to life   the universe   and everything  is  " + (40 + 2) + "";

我该如何强制 CoffeeScript 保持多行(并保留字符串插值):

 "answer \ 
 to life \
 the universe \
 and everything \
 is \
 "+(40+2)
2个回答

78

尝试使用 heredoc 语法:

myString = """
answer
to life
the universe
and everything
is
#{40+2}
"""

这将转换为以下 JavaScript 代码:

var myString;

myString = "answer\nto life\nthe universe\nand everything\nis\n" + (40 + 2);

编译后的JavaScript在视觉上实际上没有必要换行,对吧?


在JavaScript中,我想让它们在新行上可视化,但似乎这是不可能的。 - iLemming
7
@Agzam: 你为什么关心生成的 JavaScript 的外观?那些东西不是为人类消费而设计的。 - mu is too short
是的,那有什么关系吗? - nzifnab
我正在处理 XML 字符串。手动将现有的 JavaScript 代码转换为 CoffeeScript,并尝试比较结果... 这很难比较。 - iLemming
2
当你将JavaScript转换为CoffeeScript时,生成的编译JS几乎永远不会看起来相同 - 尝试对比它们是徒劳的。此外,直接将JS文本复制到CoffeeScript中通常只会导致糟糕的CoffeeScript代码。使用CoffeeScript通常可以更加优雅地完成任务。如果您真的想将旧的JS代码批量转换为CoffeeScript(并且不想使用“正确”的CoffeeScript技术编写代码),则可以使用类似http://js2coffee.org/的工具。我不确定这与XML字符串有什么关系。 - nzifnab

22

我同意在定义长字符串时保留缩进是很好的。在Coffeescript中,您可以像在Javascript中一样使用字符串相加来实现此效果:

myVeryLongString = 'I can only fit fifty-nine characters into this string ' +
                   'without exceeding eighty characters on the line, so I use ' +
                   'string addition to make it a little nicer looking.'

得出的结果为

'I can only fit fifty-nine characters into this string without exceeding eighty characters, so I use string addition to make it a little nicer looking.'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接