在 JavaScript 中使用 if 语句连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7344309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenating strings with `if` statements in JavaScript
提问by u365975
I'm attempting to set up a script to concatenate some variables inside a string if they exist, in order to place the appropriate metadata tags into a rendered HTML document.
我正在尝试设置一个脚本来连接字符串中的一些变量(如果它们存在),以便将适当的元数据标签放入呈现的 HTML 文档中。
My concatenation code is:
我的连接代码是:
data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";
I'm trying to add if
statements like the following into it (between the first and second items):
我正在尝试向其中添加if
如下语句(在第一项和第二项之间):
if (typeof metadata_title !== "undefined") {
"<title>" + metadata_title + "</title>\n"
}
if (typeof metadata_author !== "undefined") {
"<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n"
}
if (typeof metadata_date !== "undefined") {
"<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"
}
But I can't add any of these statements directly into the concatenation code
(it throws an error: Unexpected token (
).
但是我不能将这些语句中的任何一个直接添加到连接代码中(它会引发错误:)Unexpected token (
。
How best would I go about adding statements such as these into my concatenation string?
我将如何最好地将这些语句添加到我的连接字符串中?
回答by bluish
I'd use a ternary operator:
我会使用三元运算符:
data = "<html>\n"
+ "<head>\n"
+ ( typeof metadata_title !== "undefined" ? "<title>" + metadata_title + "</title>\n" : "" )
+ ( typeof metadata_author !== "undefined" ? "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
+ ( typeof metadata_date !== "undefined" ? "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" : "" )
+ "</head>\n"
+ "<body>\n"
+ "\n"
+ paras.join("\n\n")
+ "\n"
+ "\n"
+ "</body>\n"
+ "</html>"
;
回答by scessor
data = "<html>\n<head>\n"
+ (
typeof metadata_title !== "undefined" ?
"<title>" + metadata_title + "</title>\n" :
""
)
+ (
typeof metadata_author !== "undefined" ?
"<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" :
""
)
+ (
typeof metadata_date !== "undefined" ?
"<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" :
""
)
+ "</head>\n<body>\n\n"
+ paras.join("\n\n")
+ "\n\n</body>\n</html>";
回答by Demian Brecht
I might do something a little different (a little more akin to templating), mainly because I hate concatenated HTML done with Javascript:
我可能会做一些不同的事情(更类似于模板),主要是因为我讨厌用 Javascript 完成的连接 HTML:
var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";
var template = "<html>\
<head>\
<title>#title#</title>\
<meta name=\"author\" content=\"#author#\"></meta>\
<meta name=\"date\" content=\"#date#\"></meta>\
</head>\
<body>\
</body>\
</html>";
var data = template.replace("#title#", metadata_title != undefined ? metadata_title : "")
.replace("#author#", metadata_author != undefined ? metadata_author : "")
.replace("#date#", metadata_date != undefined ? metadata_date : "");
Sure, there's a verysmall amount of additional overhead, but to me, it's waymore readable.
当然,有一个非常的额外开销量小,但对我来说,它的方式更具可读性。
回答by Francisco Costa
I liked the readability of Demian Brechtanswer, but I would only change the string for a regexinstead, because the replace() function only replaces the first match (see more here: JavaScript .replace only replaces first Match)
我喜欢Demian Brecht答案的可读性,但我只会更改正则表达式的字符串,因为 replace() 函数仅替换第一个匹配项(请参阅此处的更多信息:JavaScript .replace only replaces first Match)
var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";
var template = "<html>\
<head>\
<title>#title#</title>\
<meta name=\"author\" content=\"#author#\"></meta>\
<meta name=\"date\" content=\"#date#\"></meta>\
</head>\
<body>\
</body>\
</html>";
var data = template.replace(/#title#/g, metadata_title != undefined ? metadata_title : "")
.replace(/#author#/g, metadata_author != undefined ? metadata_author : "")
.replace(/#date#/g, metadata_date != undefined ? metadata_date : "");
回答by Ray Toal
Build up the entire document into an array, then join with a "\n"
at the end. (The rationale for this is of course to not have lots of new lines scattered all about! And if you are on IE7 or less, Array#join
is considerably faster than repeated string concatenation.)
将整个文档构建成一个数组,然后以 a"\n"
结尾。(这样做的基本原理当然是没有很多新行散落一地!如果您使用的是 IE7 或更低版本,Array#join
则比重复字符串连接要快得多。)
Code here: http://jsfiddle.net/ZCbCZ/
代码在这里:http: //jsfiddle.net/ZCbCZ/
UPDATEI forgot to include the "paras" in the first fiddle. The code with the paras is here: http://jsfiddle.net/U8325/1/
更新我忘了在第一个小提琴中包含“paras”。带有参数的代码在这里:http: //jsfiddle.net/U8325/1/
For those not wishing to click through and try it out, here is the script:
对于那些不想点击并尝试的人,这里是脚本:
// Not going to define metadata_author just to be saved by typeof :-)
var metadata_title = "Hello";
var metadata_date = "2011-09-07";
// Okay 3 paras for fun
var paras = ["<p>paragraph1</p>", "<p>paragraph2</p>", "<p>paragraph3</p>"];
data = ["<html>", "<head>"]
if (typeof metadata_title !== "undefined") {
data.push("<title>" + metadata_title + "</title>");
}
if (typeof metadata_author !== "undefined") {
data.push("<meta name=\"author\" content=\"" + metadata_author + "\"></meta>");
}
if (typeof metadata_date !== "undefined") {
data.push("<meta name=\"date\" content=\"" + metadata_date + "\"></meta>");
}
data.push("</head>");
data.push("<body>");
paras.forEach(function (p) {data.push(p);}); // Requires ES5; use a for-loop if you don't have it
data.push("</body>");
data.push("<html>");
data = data.join("\n");
alert(data);