最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to construct a long string - Stack Overflow

programmeradmin7浏览0评论

I need to construct a long string with javascript. Thats how i tried to do it:

var html = '<div style="balbalblaba">&nbsp;</div>';
for(i = 1; i <= 400; i++){
   html+=html;
};

When i execute that in firefox its taking ages or makes it crash. what is the best way to do that? What is generally the best way to construct big strings in JS.

can someone help me?

I need to construct a long string with javascript. Thats how i tried to do it:

var html = '<div style="balbalblaba">&nbsp;</div>';
for(i = 1; i <= 400; i++){
   html+=html;
};

When i execute that in firefox its taking ages or makes it crash. what is the best way to do that? What is generally the best way to construct big strings in JS.

can someone help me?

Share Improve this question edited May 8, 2010 at 16:11 meo asked Apr 9, 2010 at 19:17 meomeo 31.2k19 gold badges89 silver badges123 bronze badges 1
  • Duplicate ? stackoverflow.com/questions/202605/repeat-string-javascript – Adriaan Stander Commented Apr 9, 2010 at 19:22
Add a comment  | 

4 Answers 4

Reset to default 12

I assume you mean html += html;.

If you do that, your html string's length will be 37 × 2400 = 9.5 × 10121 which is beyond the limit of any browsers, on any computers, in any[1] known universes can handle.

If you just want to repeat that string 400 times, use

var res = "";
for (var i = 0; i < 400; ++ i)
   res += html;
return res;

or

var res = [];
for (var i = 0; i < 400; ++ i)
   res.push(html);
return res.join("");

See Repeat String - Javascript for more options.


[1]: As in "this universe".

String concatenation is very slow in some browsers (coughIE6*cough*). Joining an array should be much quicker than looping with concatenation:

var arr = new Array(401);
var html = arr.join('<div style="balbalblaba">&nbsp;</div>');

Another way to do it is by create an Array of stings then using Array.join(''). This is effectively the Python way of building strings, but it should work for JavaScript as well.

var src = '<div style="balbalblaba">&nbsp;</div>';
var html = '';
for(i = 1; i <= 400; i++){
   html=+src;
};

Your code is doubling the string 400 times.

发布评论

评论列表(0)

  1. 暂无评论