-1

I have a 2D array "allcolor" in javascript. So that I initialize each row of it with a 1D array same below code.

var allcolor=[];
var color=["#f73214","#f5f714","#54f714","#141df7","#006400","#556B2F","#2F4F4F",
           "#808080","#8FBC8F","#4B0082","#9400D3","#483D8B","#1E90FF","#00BFFF", 
           "#FFFF00","#ADFF2F","#9932CC","#FF69B4","#FF1493","#8B0000","#8B4513",
           "#B22222","#CD5C5C","#E9967A","#FF8C00","#DAA520","#F0E68C","#FFFAF0",
           "#000000"];

for(p=0;p<x.length;p++){
    allcolor[p]=color;
}

When I change each element of each row of allcolor, overwrite other element of all row of allcolor. When I run this bellow code, I see that all [..][0] and all [..][4] are same value '#000000' and '#ffffff'.

console.log(allcolor);
allcolor[0][0]='#000000';
console.log(allcolor);
allcolor[0][4]='#ffffff';
console.log(allcolor);

How can I change value of one row?

jigfox
  • 18,057
  • 3
  • 60
  • 73
narges
  • 681
  • 2
  • 7
  • 26

1 Answers1

0

So, this happens, because javascript variables only store references to memory places where objects belong (kind of like pointers in C++). When you put color in the allcolor array 4 times, then they'll refer to the same object, thus if you change the value of one row, you change every row's value.

To avoid this, do

allcolor[p]=color.slice();
Bálint
  • 4,009
  • 2
  • 16
  • 27