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.

4
  • 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. Commented Feb 17, 2016 at 21:58
  • 3
    Possible duplicate of Copying array by value in JavaScript Commented Feb 17, 2016 at 21:59
  • drumOn['s' + j] will access the property drumOn.s0. Commented Feb 17, 2016 at 21:59
  • @ryanyuyu: ...which is an array of booleans, yes. Commented Feb 17, 2016 at 22:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.