对编码不熟悉。有人可以解释(“ i =(i + 1)%word.length”)
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
word[i].style.display = 'none';
i = (i + 1) % word.length
word[i].style.display = 'initial';
}
setInterval(run,800)
选择了最后一个单词后,将i重置为0(选择第一个单词)。>>
var text = document.querySelector('#text-wrap'); var word = text.getElementsByTagName('span'); var i = 0; function run(){ // hide i-th word word[i].style.display = 'none'; // set i to // if the last word is selected select the first word ( reset to 0 ) i = (i + 1) % word.length // display i-th word word[i].style.display = 'initial'; } setInterval(run,800)
我不建议这样做。 if语句更加清晰。该操作应相同:
var text = document.querySelector('#text-wrap'); var word = text.getElementsByTagName('span'); var i = 0; function run(){ word[i].style.display = 'none'; if( i+1 !== word.length ) i++; else // if i+1 === word.length i = 0; word[i].style.display = 'initial'; } setInterval(run,800)
仍然您不应该将i用作全局变量。至少使用一个在其他代码中不可能存在的变量名代替。
快速模量说明
模数是您不能迭代删除一个量时剩余的值。一些例子:
6 % 2 = 0 ( 6 - 2 - 2 - 2 = 0)
5 % 2 = 1 ( 5 - 2 -2 = 1 )
1 % 2 = 1 ( cannot substract 2 from 1 so the value is 1 )
简化示例
var word = [ '1', '2', '3'];
var i = 0;
function run(){
console.log( word[i] );
if( i+1 !== word.length )
i++;
else // if i+1 === word.length
i = 0;
}
setInterval(run,1000);
if (i < word.length - 1):
i = i + 1; // increment
else if (i == word.length - 1):
i = 0; // go back to 0