Reputation: 23149
say I have an array of objects with html strings inside (there are other things, but i'm specifically focusing on the html property of each object. e.g.
var items = [{
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}];
I need to build a string using all of these strings and I need them in the same order they're given to me, so a reverse while loop is out.
is there anything faster at building the html than the following?
var html = [];
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
html.push(items[i].html)
}
output.innerHTML = html.join('');
Upvotes: 1
Views: 6958
Reputation: 17061
This does the trick too:
var items = [
{html: '<div>test</div>'},
{html: '<div>test</div>'},
{html: '<div>test</div>'}],
newString = "";
items.forEach(function(item) {
newString = newString + item.html;
});
Demo.
Upvotes: 0
Reputation:
faster would be:
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; ++i)
html += items[i].html;
output.innerHTML = html;
Edit:
This is faster:
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; html += items[i++].html);
Upvotes: 2
Reputation: 6334
Warning this is solution could cause a lot problems. But it does give a relatively fast way to do what you want.
var items = [{
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}];
Object.prototype.toString=function(){return this.html};
items.join('');
If there is anyway to control the object that gets added to the array in the first place then you can change only that object's prototype which won't mess with the global Object.
Upvotes: -1
Reputation: 3023
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
html += items[i].html;
}
output.innerHTML = html
Simply concatenating to a string would be faster than building an array and imploding it as that technically double loops the data instead of looping it once.
Upvotes: 1
Reputation: 78971
This is much faster than yours
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
html += items[i].html;
}
output.innerHTML = html;
Upvotes: 1