Klak031
Klak031

Reputation: 49

Why all values in array after loop have same value?

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);

Upvotes: 0

Views: 97

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

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

Upvotes: 2

Related Questions