Javascript附加到变量

时间:2014-03-22 13:49:04

标签: javascript

        var gen = "            scrollwheel: true,\n"+
              "            streetViewControl: true,\n";

    if (val == "FALSE"){
                gen = "            control: false,\n";
                } else {
                gen = "            control: true,\n";
    }
gen = "            zoom: true,\n";

附加gen变量的最佳方法是什么,以便所有内容一个接一个地添加。

1 个答案:

答案 0 :(得分:4)

您可以使用+= operator作为追加字符串的便捷方式:

var gen = "            scrollwheel: true,\n"+
          "            streetViewControl: true,\n";

if (val == "FALSE"){
     gen += "            control: false,\n";
} else {
     gen += "            control: true,\n";
}
gen += "            zoom: true,\n";

注意:gen += "foo"相当于get = gen + "foo"
但在这种情况下,我认为条件运算符(?:)更简单:

var gen = "            scrollwheel: true,\n"+
          "            streetViewControl: true,\n" +
          "            control: " + (val == "FALSE" ? "false" : "true") + ",\n" +
          "            zoom: true,\n";

或者如果意图是创建JSON字符串,只需直接创建对象:

var gen = {
    scrollwheel: true,
    streetViewControl: true,
    control: val != "FALSE",
    zoom: true
};

然后使用JSON.stringify将其转换为字符串。