I have a javascript code as below.
Can someone tell what is wrong in this code?
You're using one row
array for all your entries in state
. fill
takes the value you give it and puts that value in the target array repeatedly. The value you're giving it is a reference to the single array you've created, so all of those entries end up referring to the same row, like this:
+−−−−−−−−−+ row−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−+−+−+−−>| (array) | +−−−−−−−−−+ | | | | | | | +−−−−−−−−−+ state−−−−>| (array) | | | | | | | | | 0: 0 | +−−−−−−−−−+ | | | | | | | | 1: 0 | | 0 |−−−−−+ | | | | | | | 2: 0 | | 1 |−−−−−−−+ | | | | | | 3: 0 | | 2 |−−−−−−−−−+ | | | | | 4: 0 | | 3 |−−−−−−−−−−−+ | | | | 5: 0 | | 4 |−−−−−−−−−−−−−+ | | | 6: 0 | | 5 |−−−−−−−−−−−−−−−+ | +−−−−−−−−−+ | 6 |−−−−−−−−−−−−−−−−−+ +−−−−−−−−−+
You'll need to create a new row array for each slot in state
:
let state = Array.from({length:7}, () => {
return new Array(7).fill(0);
});
state[0][3] = 2;
console.log(state);
.as-console-wrapper {
max-height: 100% !important;
}
...or with only features present in ES5:
var state = [0,0,0,0,0,0,0].map(function() {
return [0,0,0,0,0,0,0];
});
state[0][3] = 2;
console.log(state);
.as-console-wrapper {
max-height: 100% !important;
}