0

Why all values on return are the same (16)["F", 0, 0, 0, 0, 0] and on console.log(color) I am getting 16 different hex colors :S

 let color = [0, 0, 0, 0, 0, 0];
    let colors = [];
    
    for (let a = 0; a < 16; a++) {
      let x = 0;
    
      switch (a) {
        case 10:
          x = "A";
          break;
        case 11:
          x = "B";
          break;
        case 12:
          x = "C";
          break;
        case 13:
          x = "D";
          break;
        case 14:
          x = "E";
          break;
        case 15:
          x = "F";
          break;
        default:
          x = a;
      }
    
      color[0] = x;
      console.log(color);
      colors.push(color);
    }
    
    console.log(colors);

4
  • Works fine, what exactly are you expecting? Commented Jan 30, 2021 at 18:41
  • color[0] = x; is the culprit if I understand your problem. Commented Jan 30, 2021 at 18:41
  • 2
    colors.push(color); does not push a copy of the array. It pushes the same array reference each time Commented Jan 30, 2021 at 18:42
  • I am expecting to get array of first 16 hex colors. [[0,0,0,0,0,0], [1, 0,0,0,0,0], [2,0,0,0,0,0] etc... ] Commented Jan 30, 2021 at 18:44

1 Answer 1

2

Arrays are copy by reference, not values. Make a shallow copy in the push() using ..., since it's one dimensional:

let color = [0, 0, 0, 0, 0, 0];
let colors = [];

for (let a = 0; a < 16; a++) {
  let x = 0;

  switch (a) {
    case 10:
      x = "A";
      break;
    case 11:
      x = "B";
      break;
    case 12:
      x = "C";
      break;
    case 13:
      x = "D";
      break;
    case 14:
      x = "E";
      break;
    case 15:
      x = "F";
      break;
    default:
      x = a;
  }

  color[0] = x;
  console.log(color);
  colors.push([...color]);
}

console.log(colors);

Hope this is what you're looking for...

console

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.