How To Construct A Long String
I need to construct a long string with javascript. Thats how i tried to do it: var html = ' '; for(i = 1; i <= 400; i++){
Solution 1:
I assume you mean html += html;
.
If you do that, your html
string's length will be 37 × 2 = 9.5 × 10 which is beyond the limit of any browsers, on any computers, in any 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.
Solution 2:
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"> </div>');
Solution 3:
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.
Solution 4:
var src = '<div style="balbalblaba"> </div>';
var html = '';
for(i = 1; i <= 400; i++){
html=+src;
};
Your code is doubling the string 400 times.
Post a Comment for "How To Construct A Long String"