I am trying to create a generative object, filled with arrays (all 0).
//declaration of the data object
var data = {}
//initiate to fill data with keys and arrays
function init()
{
var pos = Array.apply(null,Array(16)).map(Number.prototype.valueOf,0); //creates empty array filled with 0
for(var i = 0; i < 16; i++) {
data[i] = pos;
}
}
init();
console.log(data);
This would give me a data filled with keys from 0 to 2 and each key has an array filled with 0;
{
'0': [
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
],
'1': [
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
],
'2': [
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
}
Now, when I try to modify a specific array like this:
data[0][1] = 1;
then the result will print that all arrays in all keys have been modified...
{
'0': [
0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
],
'1': [
0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
],
'2': [
0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
}
This makes no sense to me because I wanted to modify only the first array with key 0... If I create the whole object manually, the change will work fine, but if I do it this way (generative), I get this strange bug. Any ideas?