在 JavaScript 中编写多行字符串最简洁的方法是什么?
它实际上不必添加换行符,只需添加可读的内容即可。
还有比这更好的吗?
str = "line 1" +
"line 2" +
"line 3";
It doesn't really have to add newlines, just something readable.
Anything better than this?
str = "line 1" +
"line 2" +
"line 3";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
与 NickFitz 的答案几乎相同:
不同之处在于,代码的可维护性稍高一些,因为可以对行进行重新排序,而无需考虑逗号在哪里。没有语法错误。
Almost identical to NickFitz's answer:
The difference, the code is slightly more maintainable because the lines can be re-ordered without regard to where the commas are. No syntax errors.
我喜欢这个版本(与您的版本不同,只是代码格式不同):
I like this version (different than yours just in formatting of the code):
正如评论中提到
的,javascript 解析器可以很好地处理这个问题(它适用于所有主要浏览器),但不是 ECMA 脚本语法的正式部分。因此,它可能会也可能不会与压缩器、错误检查器一起工作,并且不保证在浏览器中工作。
这可能更具可读性,但并不是“最佳”方法。也许有一天 ECMA 脚本会支持像 c# 的 @"" 这样的东西。
You could do
As mentioned in the comments, javascript parsers handle this fine (it works in all major browsers), but is not officially part of ECMA Script syntax. As such it may or may not work with compressors, error checkers, and isn't guaranteed to work in browsers.
This may be more readable, but isn't the 'best' way to do it. Maybe ECMA script will support something like c#'s @"" someday.
供参考。
您建议的方式是正确的方式,并且比其他答案更好。 JsLint 仅验证您的版本。
FYI.
The way you suggest it is the correct way and better than the other answers. JsLint only validates your version.
如果您确实想要在字符串中换行,请将
.join("")
替换为.join("\n")
/If you actually want newlines in the string, then replace
.join("")
with.join("\n")
/始终如一。
无论您选择哪种方式,请在整个申请过程中以完全相同的方式进行。如果您正在开发一个已经编写了代码的应用程序,请接受他们设置的约定并遵循它。
Consistently.
Whichever way you choose, do it exactly the same way throughout your application. If you're working on an application that already has code written, accept the convention they set and go with it.
是的!您可以使用\ 字符让 JavaScript 忽略行尾字符。
然而,正如指出的Elzo Valugi,这不会使用 JSLint 进行验证。
Yes! You can use the \ character to have JavaScript ignore end of line characters.
However, as pointed out by Elzo Valugi, this will not validate using JSLint.
这仅适用于支持 E4X 支持的浏览器 - 我希望我们可以在 IE 中使用它
This will only work in browsers with E4X support - I wish we could use it in IE
以下是在使用 Chrome 进行开发时可能会有所帮助的一项内容。
尽管它可以在 Chrome 中使用,但它不适用于 Firefox。
示例用途是编写/测试 webgl 着色器。
在开发过程中,使用它会更好
稍后您可以随时使用简单的正则表达式来运行它
将该语法转换为跨浏览器版本。
Here's one that may be helpful during development when using Chrome.
This does not work for Firefox, although it works in Chrome.
Example use would be for writing/testing webgl shaders.
During development this is much nicer to work with and
later you can always run over this with a simple regexp
that converts that syntax into a cross-browser version.