开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜