我创建了一个颜色值数组,代表颜色从红到蓝的平滑过渡。将数组的反转追加到自身
现在我想让这个数组从红色到蓝色再回来。显而易见的解决方案是将数组的反转追加到数组中。
我已经写了代码来做到这一点,但它不工作,因为我理解它应该。相反,它会创建反转阵列,重复。它不是“从红到蓝,从蓝到红”,而是从“蓝到红,蓝到红”。
显然,在JavaScript中有一些数组的行为,我还没有掌握。
我该怎么做?
我第一次尝试是这样的:
colors = colors.concat(colors.reverse());
基于第一计算器的答案,我想这一点:
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);
打我吧,+1 :-)当然 – 2010-12-23 12:16:41