JavaScript matrix bounds are incorrect

I need to write a function that returns a function that generates a 2D array. The function mult(x,y) should return a function to generate a multiplication table, and calling generate_matrix() should return the matrix.

    function mult(x,y){
            function generate_matrix(){
                var matrix = new Array(x);
                for(var k = 0; k < x+1; k++){
                    matrix[k] = new Array(y);
                }
                for(var i = 0; i < x+1; i++){
                    for(var j = 0; j < y+1; j++){
                        matrix[i][j] = i*j;
                    }
                }
                return matrix;
            }
            return generate_matrix;
        }

For some reason, the matrix is 100 times larger than it should be. For example, if I set var matrix = mult(5,5), then call matrix(), I am given an array of size 50×50 instead of an array of size 5×5.

  • Not able to understand the deleting process while writing todo list in AngularJS
  • Javascript array of ranges reduction
  • Javascript - Merge two dimensional array with unique result
  • Looking for matches in multi-dimensional arrays inJavascript
  • Jquery splits huge array into many new callbacks while parsing
  • Find the dimensionality of a javascript array
  • I set var m = mult(2,2), then call m(), I should get the following 2D array:

    [[0,0,0],[0,1,2],[0,2,4]]
    

  • Javascript array : why is this not valid?
  • Is there a way to build a string out of an array in a specific order?
  • JSON data being received in an incomplete format in php?
  • Comparing my array works until the array has multiple values in it
  • How to find part of a string in array jQuery
  • Javascript: split string into 2d array
  • One Solution collect form web for “JavaScript matrix bounds are incorrect”

    Please try this, I think this is what you want.

    You can test this on following link : http://jsfiddle.net/BhaveshKachhadiya/Wt5gQ/33/

    function mult(x, y) {
                var matrix = new Array(x);
                for (var k = 0; k < x + 1; k++) {
                    matrix[k] = new Array(y);
                }
                for (var i = 0; i < x + 1; i++) {
                    document.getElementById('output').innerHTML = document.getElementById('output').innerHTML + "[";
                    for (var j = 0; j < y + 1; j++) {
                        matrix[i][j] = i * j;
                        document.getElementById('output').innerHTML = document.getElementById('output').innerHTML + matrix[i][j] + ",";
                    }
                    document.getElementById('output').innerHTML = document.getElementById('output').innerHTML + "]" + "<br/>"
                }
                alert(matrix);
                return matrix;
            }