用JavaScript中的`if`语句连接字符串 [英] Concatenating strings with `if` statements in JavaScript

查看:120
本文介绍了用JavaScript中的`if`语句连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个脚本来连接字符串中的一些变量(如果它们存在),以便将相应的元数据标记放入呈现的HTML文档中。

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.

我的串联代码是:

data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";

我正在尝试添加 if 语句如下所示(第一项和第二项之间):

I'm trying to add if statements like the following into it (between the first and second items):

    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 ().

我最好如何将这些语句添加到我的串联字符串中?

How best would I go about adding statements such as these into my concatenation string?

推荐答案

我使用三元运算符

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

这篇关于用JavaScript中的`if`语句连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆