我正在尝试制作6种随机RGB颜色,所以我有2个循环,内部的一个重复3次,因为我想要3个数字,外部的一个重复6次,因为我想要6个颜色。当我将3个随机数的小数组推入大数组时,它推的是最后一个数组而不是前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)
}
输出:
(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???
答案 0 :(得分:2)
在此处将tempArray
附加到colorArray
时:
colorArray.push(tempArray)
这不会向tempArray
添加colorArray
的副本;它向tempArray
到colorArray
添加了 reference 。这意味着如果以后更改此tempArray
的元素,则colorArray
内的数组也将更改,因为它们是同一数组。
因此,在循环中,您将对colorArray
的同一数组的引用添加了六次,这就是colorArray
的所有六个元素都相同的原因。
您可以通过在循环{{1}中移动let tempArray = []
来解决此问题,以便每次创建一个新数组添加到for
中。
答案 1 :(得分:1)
在您的tempArray
中按下colorArray
后,您对其进行了更改。 colorArray
仅包含对tempArray
的引用,因此colorArray
内部的每个元素最后都相同。
如何修复:
在外部tempArray
循环中声明for
,以便每次迭代都有一个新实例:
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)
}
顺便说一句,您应该将Math.random()
与256而不是255相乘,否则就排除255。
答案 2 :(得分:0)
使用concat函数,如下所示:
var newArray = colorArray.concat(tempArray)