Nestor Britez Nestor Britez - 7 months ago 40
Javascript Question

Weird behavior in increment operator

I was playing with javascript trying to create a classic spiral matrix like this one:

01 02 03 04
12 13 14 05
11 16 15 06
10 09 08 07


But when I debugged my code, I noticed something weird:
enter image description here
The matrix array is filling the space
[1][x]
when
j
is
0


How is that possible?

What is the explanation for this behavior?

Here is the piece of code:

var draw = function(direction, dim) {
var directions = ['right', 'down', 'left', 'up'];
var __matrix = Array(dim[0]).fill(Array(dim[1]).fill(0));
var fill = {};

fill.right = function(nextIndex, matrix, j, i, value) {
if(value === (dim[0] * dim[1])) { return matrix; }
if(matrix[j][i] === 0) { matrix[j][i++] = value++; }
else { i--; nextIndex++; }
debugger;
return fill[directions[nextIndex]].apply({}, arguments);
}

fill.down = function() { }; //todo
fill.left = function() { }; //todo
fill.up = function() { }; //todo

return fill[direction](directions.indexOf(direction), __matrix, 0, 0, 1);
};

console.log(draw('right', [4,4]));

Answer

This has nothing to do with the increment operator. You are writing on the 0 index, it just so happens that every array in your matrix array is the same array reference.

var arr = Array(4).fill(Array(4).fill(0))
//arr[0] === arr[1] === arr[2] === arr[3]
arr[0][0] = 'Hey';
console.log(arr[1][0]) //also 'Hey'
Comments