我创建了一个颜色值数组,表示颜色从红色到蓝色的平滑过渡。
现在我希望这个数组能够让你从红色变为蓝色并再次返回。显而易见的解决方案是将数组的反转附加到数组中。
我已编写代码来执行此操作,但它无法正常工作,因为我理解应该这样做。相反,它正在创建反向数组,重复。而不是“红到蓝,从蓝到红”,而是“蓝到红,蓝到红”。
显然,javascript中有一些我尚未掌握的数组行为。
我该怎么办?
我的第一次尝试就是:
colors = colors.concat(colors.reverse());
基于第一个stackoverflow答案,我尝试了这个:
var arrayCopy = colors;
arrayCopy.reverse();
colors = colors.concat(arrayCopy);
但这会产生相同的结果!
对于上下文,这是周围的代码:
///////////////////////////////////////////////////////////
// Creating the array which takes you from Red to Blue
//
var colorSteps = 400;
var startColor = [255, 0, 0];
var endColor = [0, 127, 255];
var steps = new Array();
var j = 0;
for (j = 0; j < 3; ++j) {
steps[j] = (endColor[j] - startColor[j]) / colorSteps;
}
var colors = Array();
for (j = 0; j < colorSteps; ++j) {
colors[j] = [
Math.floor(startColor[0] + steps[0] * j),
Math.floor(startColor[1] + steps[1] * j),
Math.floor(startColor[2] + steps[2] * j)
];
}
////////////////////////////////////////////////////////
// Here's the bit where I'm trying to make it a mirror
// of itself!
//
// It ain't working
//
colors = colors.concat(colors.reverse());
///////////////////////////////////////////////////////
// Demonstrating what the colors are
//
j = 0;
var changeColorFunction = function () {
if (++j >= colors.length) {
j = 0;
}
var colorName = "rgb(" + colors[j][0] + ", " + colors[j][1] + ", " + colors[j][2] + ")";
debugText.style.background = colorName;
debugText.innerHTML = j;
}
setInterval(changeColorFunction, 10);
答案 0 :(得分:9)
问题:
colors = colors.concat(colors.reverse());
...是colors.reverse()
变异colors
数组本身,这意味着你将反向数组附加到已经反转的数组。试试这个:
colors = colors.concat(colors.slice().reverse());
答案 1 :(得分:3)
首先将colors
阵列复制到某处。 reverse
更改数组本身,而不仅仅返回一个已恢复的数组。
<强>更新强>
代码示例:
colors.concat(colors.slice(0).reverse());