It resets i to 0 ( to select the first word ) after the last word is selected.(选择最后一个单词后,它将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)
I would not recommend doing it like this.(我不建议这样做。)
An if statement is much clearer.(if语句更加清晰。) This should do the same:(该操作应相同:)
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)
Still you shouldn't use i as a global variable.(仍然您不应该将i用作全局变量。)
At least use a variable name that is incredibly unlikely to exist in other code instead.(至少使用一个在其他代码中几乎不可能存在的变量名。)
a quick modulus explanation(快速模数说明)
the modulus is what is leftover when you cannot iteratively remove an amount.(模数是无法迭代删除金额时剩余的金额。)
Some examples:(一些例子:)
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 )
simplified example(简化的例子)
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…