Search code examples
javascripthtmlloopsdhtmlon-screen-keyboard

Javascript: Trying to build an onscreen keyboard with a loop but I get an "allocated size overflow" message


<html>
<head>
    <script type = "text/javascript">
        var fst_row = ["q","w","e","r","t","y","u","i","o","p"];
        var snd_row = ["a","s","d","f","g","h","j","k","l"];
        var thd_row = ["z","x","c","v","b","n","m"];

        function insert_fst_row(){
            document.getElementById("my_key").innerHTML = keyboard(snd_row);  
        } //inserts first row of letters of the keyboard when user clicks button.

        function keyboard(array){
            var key = "";
            key += "<table>";
            for (var row = 1; row = 1; row++){
                key +=      "<tr>";
                for (var col = 1; col <= array.length; col++){
                    key +=      "<td><input type = 'button' value = 'array[i]'/></td>"; ** //Error here.
                    }
                key +=      "</tr>";
                }

            key += "</table>";
            return key;
        }

    </script>
</head>

<body>
    <input type = "text" name = "text" id = "text"/>
    <input type = "button" value = "insert key" onclick = "insert_fst_row()"/>
    <p id = "my_key"></p>
</body>

I'm trying to make an onscreen keyboard using a loop, so I put each row of letters in a separate array. However I'm having trouble making the keyboard appear when I click the button. Instead when it runs, it prints out an error stating "allocation size overflow" and it refers to the line indicated in the code with **. What does this mean and how can it be resolved?


Solution

  • The problem is here:

    // ---------------vvvvvvv
    for (var row = 1; row = 1; row++) {
    

    On every loop iteration row = 1 will always be non false (i.e. 1), hence your loop will never stop executing. This infinite loop leads to stack memory overflow. In ordinary cases the second section of for loop carries a clause that will stop iterations, e.g. row < number_of_rows.