Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - “ i =(i + 1)%word.length”背后的逻辑是什么(What is the Logic behind “ i = (i + 1) % word.length ”)

Im new to Coding.(我是新来的编码。)

can someone explain ("i = (i + 1) % word.length")(有人可以解释吗(“ 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)  
  ask by Mukesh Saravanan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...