I've encountered a perplexing issue while working with a two-dimensional array named "grid" that holds objects known as "squares". In this scenario, each square simply keeps track of how many times it has been selected (clicked).
After initializing the grid, the structure appears as follows...
this.grid = [
[{"selected":0},{"selected":0},{"selected":0}]
,[{"selected":0},{"selected":0},{"selected":0}]
,[{"selected":0},{"selected":0},{"selected":0}]
];
The problem arises when attempting to increment the "selected" value of a single object in the grid using this.grid[x][y].selected += 1;
. Instead of updating only one object, all values in the corresponding row get incremented, resulting in...
[ [{"selected":0},{"selected":1},{"selected":0}]
,[{"selected":0},{"selected":1},{"selected":0}]
,[{"selected":0},{"selected":1},{"selected":0}] ]
This unintended behavior is not what I intended. :(
The root cause seems to lie within the process of creating the grid's array structure, as manipulating individual objects works when hard-coded. What could be causing this issue and how can it be resolved?
Below is the JavaScript code snippet...
function GridClass () {
this.$grid = $('.grid');
this.grid = [[]];
this.createGrid = function () { // Suspected source of the issue
var baseSize = 3;
this.grid = [];
var blankYArray = [];
for (var y = 0; y < baseSize; y++) {
blankYArray.push({
"selected" : 0
});
}
for (var x = 0; x < baseSize; x++) {
this.grid.push(blankYArray);
}
}
this.selectSquare = function (x, y) {
this.grid[x][y].selected += 1;
this.drawGrid();
}
this.drawGrid = function () {
var h = "", rowClass = "";
var xLen = this.grid.length;
var yLen = this.grid[0].length;
for (var y = 0; y < yLen; y++) {
for (var x = 0; x < xLen; x++) {
var g = this.grid[x][y];
h += '<div class="' + rowClass
+ ' alt' + g.selected + '"'
+ ' data-x="' + x + '"'
+ ' data-y="' + y + '">'
+ x + "," + y + '</div>';
}
h += '<br />';
}
this.$grid.html(h);
}
this.createGrid();
this.drawGrid();
}
grid = new GridClass();
grid.$grid.on("click", "div", function(e){ // Click event for each square
var $thisSquare = $(this);
var x = $thisSquare.data("x");
var y = $thisSquare.data("y");
grid.selectSquare(x, y);
});
A simple HTML layout:
<div id="gridFrame"><div class="grid"></div></div>
To view the complete setup along with CSS styles, visit the jsfiddle link provided: http://jsfiddle.net/luken/fu4yW/