Nordax Nordax - 16 days ago 9
Javascript Question

I can't store values of adjacent elements in an array

I'm trying to build a minesweeper game and I'm currently writing code for finding adjacent elements in array, it works but the problem is the items won't be stored in the array. It only stores the first elements.

I can't store the adjacent cells in the board array. it only stores the first element [5.3] and don't store the other adjacent cells.

For simplicity, I will replace the arrays of bombs with simple values

Here is what I've tried



$(document).ready(function() {
adjSquares();

});

var mines = {
fields: [[4,4],[3,9],[2,1]],

};
var board = {
x: null,
y: null,
fields: []
};

var adjSquares = function() {
var adj = [
[-1, 1],
[-1, 0],
[-1, -1],
[0, 1],
[0, -1],
[1, 1],
[1, 0],
[1, -1]
];
$.each(mines.fields, function(i, v) {
/* iterate through array or object */

$.each(adj, function(index, val) {
/* iterate through array or object */
var xx = board.x;
var yy = board.y;

if (v[0] + val[0] > 0 && v[0] + val[0] <= 9 && v[1] + val[1] > 0 && v[1] + val[1] <= 9) {
xx = v[0] + val[0];
yy = v[1] + val[1];
board.fields = [xx, yy];

}

});


});
console.log(board.fields);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




Answer
boards.fields = [xx, yy];

should be:

boards.fields.push([xx, yy]);

Your code was just overwriting the array each time through the loop. You need to use .push() to add a new element to the array.

The other problem is that you're using the same mines.x and mines.y each time through the outer loop. You should be using the elements that you're iterating over:

var x = v[0];
var y = v[1];