0

Edited to include more info about what I'm trying to achieve.

The code below works fine, but when I uncomment the boardGen:.. and board:.. sections to make board of flexible size, no board is created, or it's of 0 dimensions (no error). Could someone please explain why, and tell me how to make it work properly?

$(document).ready(function () {

    var app = {

        // define inital matrix
        // to do: build helper function to make arbitary size grid
        board : [[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]],

        // boardGen : function (rows, cols) {
            // var array = [],
            // row = [];
            // while (cols--)
                // row.push(0);
            // while (rows--)
                // array.push(row.slice());
            // return array;
        // },

        // board : function () {
            // return app.boardGen(6, 6);
        // },

        init : function () {
            // on startup
            app.createCells();
            app.main();
        },

        createCells : function () {
            // create cells and populate
            var html = '<table>';
            for (var i = 0, len = app.board.length; i < len; ++i) {
                html += '<tr>';
                for (var j = 0, rowLen = app.board[i].length; j < rowLen; ++j) {
                    html += `<td class="cell" data-gridpos="[${i}, ${j}]">`;
                    html += `${app.board[i][j]}</td>`;
                }
                html += "</tr>";
            }
            html += '</table>';
            $('#instructions').after(html);
        },

        numNeighbours : function (arr, coords) {
            var row = coords[0];
            var col = coords[1];
            var neighbours = 8;
            var offsets = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
            for (offset of offsets) {
                // prevent errors for non-existant indices
                try {
                    neighbour = arr[row + offset[0]][col + offset[1]];
                } catch (err) {
                    neighbour = undefined;
                }
                if (!neighbour) {
                    neighbours--;
                }
            }
            return neighbours;
        },

        main : function () {
            var coords = [];
            $(document).on('click', '.cell', function () {
                // get data for current cell
                coords = $(this).data('gridpos');
                // highlight current cell
                $(this).css('background-color', 'lightgray');
                $('td').not(this).css('background-color', '');
                // update info re neighbours
                $('#info').html('Touching: ' + app.numNeighbours(app.board, coords));
                // console.log(app.numNeighbours(coords));
                // toggle values in cells and update board
                if (app.board[coords[0]][coords[1]] == 1) {
                    app.board[coords[0]][coords[1]] = 0;
                    $(this).html('0')
                } else {
                    app.board[coords[0]][coords[1]] = 1;
                    $(this).html('1')
                }
            });
        }
    };
    app.init();
});
3
  • 4
    Cause properties in an object literal aren't defined until you close that object, and finish creating it. Commented Oct 12, 2016 at 16:07
  • You probably want to say board: function() { return this.boardGen(6,6); }. Commented Oct 12, 2016 at 16:13
  • board: function() { return this.boardGen(6,6); } works, but I can't use board within the object when I do this, which I can if define board manually as an array of arrays. It's very confusing, since I use app.this and app.that throughout the object and it seems to work. Commented Oct 12, 2016 at 16:36

1 Answer 1

1
  1. The object literal gets evaluated
  2. An object is created
  3. The object is assigned to app

You can't read the value of app during step 1, since it doesn't have a value until step 3.

Sign up to request clarification or add additional context in comments.

3 Comments

The (edited) code above has lots of references to app.someFunction and app.someProperty within the object definition. Doesn't that mean it's at least partially evaluated before it's created? Not challenging your answer, just trying to get some clarity of understanding.
@Robin — It has those inside functions. They are evaluated when the function is called not when it is defined.
… and the edited question is a completely different one to the one that I answered two hours ago. The new one seems to boil down to how slice works and not how to reference an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.