49

这个字符串怎么来的

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

编译成

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

如何强制 coffescript 保持多行(保持字符串插值完整):

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

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中的换行符上并没有任何意义,是吗?

于 2013-10-15T19:16:30.920 回答
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.'
于 2014-02-10T18:51:03.087 回答