ngplayground
ngplayground

Reputation: 21667

Javascript append to variable

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

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

What would be the best way to append the gen variable so that everything gets added one after the other.

Upvotes: 0

Views: 51

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149098

You could use the += operator as a convenient way to append strings:

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

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

Note: gen += "foo" is equivalent to get = gen + "foo".
But in this case, I think the conditional operator (?:) is simpler:

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

Or if the intent is to create a JSON string, just create the object directly:

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

And then turn it into a string using JSON.stringify.

Upvotes: 4

Related Questions