How to build a long string

I need to build a long string with javascript. Here is how I tried to do this:

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

When I execute this in firefox, it takes age or makes it crash. What is the best way to do this? This is usually the best way to build large strings in JS.

Can someone help me?

+3
source share
4 answers

I guess what you mean html += html;.

If you do this, the string length htmlwill be 37 times 2 400 = 9,5 & times; 10 121 which goes beyond any browsers, on any computers, in any [1] known universes.

400 ,

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

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

. Repeat String - Javascript.


[1]: " ".

+12

(coughIE6 * cough *). , :

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

Another way to do this is to create Arraybites and then use Array.join(''). This is an effective Python way of building strings, but it should work for JavaScript too.

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

Your code doubles the line 400 times.

0
source

Source: https://habr.com/ru/post/1740509/


All Articles