开发者

Is there a javascript equivalent of .= for self concatenating?

开发者 https://www.devze.com 2022-12-23 09:29 出处:网络
Rather than doing my_var = my_var+\'extra string\'; is there a shorthand metho开发者_Go百科d like .= in php?Use +=

Rather than doing

my_var = my_var+'extra string';

is there a shorthand metho开发者_Go百科d like .= in php?


Use +=

var s = 'begin';
s += 'ning';


Performance Tip (note — this advice is valid for IE6, but it's no longer worth worrying about in 2014)

If you're writing some Javascript code to build up a long string (say, a fairly big block of HTML, or a long parameter list for an ajax request), then don't get in the habit of doing this:

var longString = "";
for (var i = 0; i < someBigNumber; ++i) {
  if (i > 0) longString += "<br>" + whatever;
  longString += someMoreStuff();
}

As the longString gets longer and longer, Internet Explorer will puff harder and harder on each iteration of the loop. Even when someBigNumber isn't really that big, the performance of that loop can be really terrible.

Luckily, there's an easy alternative: use an array:

var accumulator = [];
for (var i = 0; i < someBigNumber; ++i) {
  accumulator.push(someMoreStuff());
}
var longString = accumulator.join("<br>" + whatever);

Way, way faster in Internet Explorer than repeated string appends.


+=

Example:

my_var += "extra string";


Yes: my_var += 'extra string';

0

精彩评论

暂无评论...
验证码 换一张
取 消