0

I have arrays within objects full of false values.

var drumOn = {}, bassOn = {}, synthOn = {}, keysOn = {};
var fal = [];    
for(var j=0; j<16; j++){
  fal.push(false);
}

for(var j=0; j<0; j++){
  drumOn['s'+j] = (fal);
  bassOn['s'+j] = (fal);
  synthOn['s'+j] = (fal);
  keysOn['s'+j] = (fal);
}

then later I try adding one true value to one array

drumOn['s'+ 0][0] = true;

This adds a true value to the first element of all the arrays within drumOn and within the other objects too.

The only other thing I'm doing with these objects is checking

    if(bassOn['s' + i][j])

I was doing this with arrays within arrays and I had the same problem.

This is crazy, I've tried so many things but it makes no sense.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • You are loading the objects all with the *same* array. They all reference the *same* `fal` array. So, when you edit one, they all get edited. – gen_Eric Feb 17 '16 at 21:58
  • 3
    Possible duplicate of [Copying array by value in JavaScript](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – JJJ Feb 17 '16 at 21:59
  • `drumOn['s' + j]` will access the __property__ `drumOn.s0`. – ryanyuyu Feb 17 '16 at 21:59
  • @ryanyuyu: ...which is an array of booleans, yes. – gen_Eric Feb 17 '16 at 22:00

1 Answers1

3

Copying array by value in JavaScript

for(var j=0; j<0; j++){
  drumOn['s'+j] = fal.slice();
  bassOn['s'+j] = fal.slice();
  synthOn['s'+j] = fal.slice();
  keysOn['s'+j] = fal.slice();
}

slice returns a copy of the array. In your example, all of the items are pointing to the same original array fal. You need to duplicate it.

Community
  • 1
  • 1
Jeff
  • 24,623
  • 4
  • 69
  • 78