Reputation: 99
I am trying to make 6 random RGB colors, So I have 2 loops, inner one is only going to repeat 3 times because I want 3 numbers, outer one will repeat 6 times because I want 6 colors. When I push my small array on 3 random numbers onto a big array, its pushing the last array instead of the first 5.
let colorArray = []
makeSixColors();
function makeSixColors() { //Making 6 random color RGBS
let tempArray = []; //storing rgbs in an array, then storing that in an array
for (let j = 0; j < 6; j++) {
for (let i = 0; i < 3; i++) {
tempArray[i] = Math.floor((Math.random() * 255));
}
colorArray.push(tempArray)
console.log(colorArray[j])
}
console.log(colorArray)
}
OUTPUT:
(3) [65, 202, 231]
(3) [15, 147, 151]
(3) [225, 123, 121]
(3) [247, 17, 107]
(3) [144, 225, 191]
(3) [188, 61, 122] //My 6 small arrays
(6) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) [188, 61, 122]
1: (3) [188, 61, 122]
2: (3) [188, 61, 122]
3: (3) [188, 61, 122]
4: (3) [188, 61, 122]
5: (3) [188, 61, 122] //The big Array im pushing on.. Why only the last array???
Upvotes: 0
Views: 88
Reputation: 15
Use the concat function,like this:
var newArray = colorArray.concat(tempArray)
Upvotes: 0
Reputation: 83
When you append tempArray
to colorArray
here:
colorArray.push(tempArray)
This doesn't add a copy of tempArray
to colorArray
; it adds a reference to tempArray
to colorArray
. This means that if the elements of this tempArray
are later changed, the array inside colorArray
will change as well, since they are the same array.
So, in your loop, you are adding a reference to the same array to colorArray
six times, which is why all six elements of colorArray
are the same.
You can fix this by moving let tempArray = []
inside of your for
loop, so that it creates a new array to add to colorArray
every time.
Upvotes: 2
Reputation: 141
After you pushed tempArray
in your colorArray
, you changed it. colorArray
only contains a reference to tempArray
, so every element inside of colorArray
is the same in the end.
How to fix it:
Declare tempArray
inside of your outer for
loop so you have a new instance with each iteration:
function makeSixColors() {
for (let j = 0; j < 6; j++) {
let tempArray = [];
for (let i = 0; i < 3; i++) {
tempArray[i] = Math.floor((Math.random() * 255));
}
colorArray.push(tempArray)
console.log(colorArray[j])
}
console.log(colorArray)
}
By the way, you should multiply Math.random()
with 256 instead of 255, otherwise you exclude 255.
Upvotes: 1