猿问

为什么在下面的例子中使用 ">=" 不起作用 为什么我们必须使用“-1”?

所以我只是在学习和练习 Javascript 以及 javascript 库。在这个例子中,我正在使用 JQuery。这个例子只是一个简单的引用旋转器(你想怎么称呼它的转换器)。代码工作正常。我的问题是匿名函数中的 if 语句(在fadeOut 方法中)。if 语句中的参数是:


currentQuote == allQuotes.length - 1

为什么必须这样写而不是


currentQuote >= allQuotes.length

不应该使用大于或等于以完全相同的方式工作吗?如果没有,为什么不呢?整个代码如下。


//HTML


<body>

  <div class="quote-holder">

    <blockquote>

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do 

    </blockquote>

    <blockquote>

     Ut enim ad minim veniam, quis nostrud exercitation ullamco 

    </blockquote>

    <blockquote>

      Duis aute irure dolor in reprehenderit in voluptate velit esse 

    </blockquote>

  </div>

</body>

//CSS


.quote-holder {

  width: 30%;

}


blockquote {

  display: none;

}


blockquote:first-of-type {

  display: block;

}

//javascript jquery


let allQuotes = $("blockquote");

let currentQuote = 0;


function changeQuote(){

  $(allQuotes[currentQuote]).fadeOut(200, function(){if(currentQuote == allQuotes.length - 1){

    currentQuote = 0;

  }else {

    currentQuote++;

  }

    $(allQuotes[currentQuote]).fadeIn(200)});



}


let quoteTimer = setInterval(changeQuote, 3000)


30秒到达战场
浏览 187回答 1
1回答

Qyouu

因为只要数组位置到达末尾,循环就需要重置。否则它将始终显示第一个位置。如果数组长度是 5. 位置是 [0],[1],[2],[3],[4] 所以4是最后一个元素,它是:array.length - 1.在您的问题的功能中,您需要将位置设置为0,以便您可以让引号循环不断旋转。我用评论分步解释了更多。let allQuotes = $("blockquote");let currentQuote = 0;function changeQuote(){&nbsp; $(allQuotes[currentQuote]).fadeOut(200, function(){&nbsp; if(currentQuote == allQuotes.length - 1){ //if last position&nbsp; &nbsp; currentQuote = 0; //reset&nbsp; }else { //else&nbsp;&nbsp; &nbsp; currentQuote++; // go next&nbsp; }&nbsp; &nbsp; $(allQuotes[currentQuote]).fadeIn(200)});}let quoteTimer = setInterval(changeQuote, 3000).quote-holder {&nbsp; width: 30%;}blockquote {&nbsp; display: none;}blockquote:first-of-type {&nbsp; display: block;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><body>&nbsp; <div class="quote-holder">&nbsp; &nbsp; <blockquote>&nbsp; &nbsp; &nbsp; Hello&nbsp;&nbsp; &nbsp; </blockquote>&nbsp; &nbsp; <blockquote>&nbsp; &nbsp; &nbsp;How are you?&nbsp;&nbsp; &nbsp; </blockquote>&nbsp; &nbsp; <blockquote>&nbsp; &nbsp; &nbsp; Good Thanks&nbsp;&nbsp; &nbsp; </blockquote>&nbsp; </div></body>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答