我正在创建一个函数,使文本变成彩虹色。
我有两个数组。一个用于颜色,一个用于字符串。
我基本上想做的是根据需要多少次循环遍历颜色,具体取决于文本的数量。
var colors = ['blue', 'red', 'green', 'black', 'orange', 'purple'];
function colorText(word) {
var slicedText = word.split('');
var rainbowText= '';
if (typeof(word) !== 'string') {
alert('Thats not a word!');
} else {
for (var i = 0; i < slicedText.length; i++ ) {
rainbowText += '<span style="color:' + colors[i] + ';">' + slicedText[i] + '</span>';
}
document.getElementById('text-input').innerHTML = rainbowText;
}
}
colorText('this is a really long text');
<div id="text-input">
</div>
最佳答案
当 slicedText.length
大于 colors.length
时,您的索引超出了颜色数组的范围。如果所需的行为是在到达颜色末尾后从索引 0 开始,请使用模运算符。
颜色[ i % colors.length ]
var colors = [ 'blue', 'red', 'green', 'black', 'orange', 'purple' ];
function colorText(word) {
var slicedText = word.split( '' );
var rainbowText = '';
if (typeof( word ) !== 'string') {
alert('Thats not a word!');
} else {
for (var i = 0; i < slicedText.length; i++) {
rainbowText += '<span style="color:' + colors[ i % colors.length ] + ';">' + slicedText[ i ] + '</span>';
}
document.getElementById( 'text-input' ).innerHTML = rainbowText;
}
}
colorText( 'this is a really long text' );
<div id="text-input">
</div>
关于javascript - 多次循环一个数组,直到完成第二个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988191/