coffeescript多行字符串编译成多行字符串

时间:2013-10-15 19:12:01

标签: coffeescript

为什么这个字符串

"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)

2 个答案:

答案 0 :(得分:72)

尝试使用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中换行,是吗?

答案 1 :(得分:18)

我同意在定义长字符串时能够保留缩进很好。您可以在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.'