“i =(i< arr.length)?i:0”的目的是什么?

时间:2015-08-14 17:19:26

标签: javascript image

我无法理解这是如何改变JavaScript中的图像的? 主要是我遇到麻烦这条线

PHP Fatal error:  Call to undefined method Illuminate\Console\OutputStyle::setFormat()

如何重置并决定图像:

i = (i < images.length) ? i : 0;

3 个答案:

答案 0 :(得分:3)

它被称为三元运算符。打破这一行:

i = i < images.length ? i : 0;

......这是正在发生的事情。该声明基本上是在说:

 i = (if this is true) ? (assign this value) : (otherwise assign this);

...所以如果“i”小于“images.length”,它将保持其值(i = i),否则,它将重置(i = 0)。

答案 1 :(得分:3)

i = i < images.length ? i : 0;确保i的值仍然是有效的数组索引 - 如果其值超过i,它会将images.length的值重置为0 - 因此,允许一个循环遍历images数组。

答案 2 :(得分:1)

这很有道理。我会解释一下。

var i = 0; //the position of the image in the array "images"

//set the interval. 
//After three seconds call "fadeDivs"
setInterval(fadeDivs, 3000); 

function fadeDivs() {

    //If the value of i is not longer than the length
    //of the images array, then use the current value of i
    //If the value is greater than the length of images
    //reset the value of i to 0
    i = i < images.length ? i : 0; 

    //find the top image and fade it out
    $('.product img').fadeOut(100, function(){

        //now that it is faded out, change the src
        //attribute to the next image url in the array
        $(this).attr('src', images[i]).fadeIn(100);

    })

    //increment i for the next image image url
    i++;
}

在我发布原始答案后,看起来问题是为了清晰而编辑的。是的,正如其他人所说 - 三元运营商。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

这基本上是一个返回值的if / then语句。下面的两行代码在功能上是相同的,但三元运算符更优雅。

i = function(){if(i<images.length){return i}else{return 0}}()

i = i < images.length ? i : 0

希望这有帮助。

相关问题