Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught RangeError: Invalid string length when appending to a string in JavaScript

So basically I've been working on a small personal project of mine in Javascript, and I've hit a snag. I'm trying to generate a list in HTML from a 2D array using Javascript. Here is my code:

function generatePageFromArray(page, array){
var entry, i, j;
for (i = 0; i < array.length; ++i) {
    entry = array[i];
    for (j = 0; j < entry.length; j = j + 2) {
        page = page + '<tr>'+
                    '<td class="favoritesContainer"><input type="checkbox" class="favorites"></input></td>';
        page = page +  '<td class="english">' + entry[j,0] + '</td>';
        page = page +  '<td class="spanish">';
        if (entry[j,1].indexOf("|") > 0){
            var spanishTerms = entry[j,1].split("|");
            var strLength = spanishTerms.size;
            for (i = 0; i < strLength; i++){
                page = page.concat(spanishTerms[i] + '<br>');   
            }
        }
        else{
            page = page + entry[j,1];
        }
        page = page + '</td>'
        page = page + '</tr>';         
    }
}
return page;}

It keeps throwing a Uncaught RangeError: Invalid string length on this line:

page = page + '<tr>'+
                    '<td class="favoritesContainer"><input type="checkbox" class="favorites"></input></td>';

I have no idea why. I've also tried using .concat() to append, but nothing.

like image 219
axtscz Avatar asked Mar 08 '15 01:03

axtscz


1 Answers

Your 2-D array accesses are incorrect, but the main problem is that you're re-using the variable i in an inner loop:

for (i = 0; i < strLength; i++){
    page = page.concat(spanishTerms[i] + '<br>');   
}

That i will be the same i as in your outer loop. Thus, the error you're getting is telling you that you're building up a massive string that exceeds the capacity of the runtime system. Declare a new variable for that loop.

Accessing a value from an array of arrays requires two sets of [ ]:

entry[j][0]
like image 96
Pointy Avatar answered Oct 15 '22 22:10

Pointy