开发者

What does this expression mean in javascript?

开发者 https://www.devze.com 2023-03-14 18:12 出处:网络
$(\'.blocks\',\'#grid\').each(function (i) { $(this).stop().css({opacity:0}).delay(100).animate({ \'opacity\': 1
$('.blocks','#grid').each(function (i) {
              $(this).stop().css({opacity:0}).delay(100).animate({
                'opacity': 1
              }, {
                duration: 2000,
                complete: (i !== row * cols - 1开发者_C百科) ||
                function () {
                  alert('done');
                }

              });
            });

What does the "||" operator mean in the "complete" property of the animate function?


It exploits short circuit evaluation. While the left hand side is truthy it won't bother evaluating the right hand side.

This is because with an OR, if one condition is truthy, it doesn't need to bother with additional conditions because it already knows enough information to answer the condition. They are also evaluated from left to right.

Also, in JavaScript, instead of the condition returning true or false, it returns the last operand it evaluated. You can see why this is useful.


|| is a logical operator http://www.w3schools.com/js/js_comparisons.asp

it will 'favor' the left hand side until the left hand condition is not met anymore, at which point it will execute the right side, which is an anonymous function that executes an alert.


It's the logical OR operator, but it only evaluates the right-hand expression if the left-hand expression is false.

If the left-hand expression is true then it knows that the whole expression evaluates to true, so it doesn't bother evaluating (or executing) the right-hand expression.


The expression seems to be a fade in.

The logical OR || is similar to an else case of an if statement. If the left side evaluates to false, the function is created and an alert is called.


Given:

  • (i !== row * cols - 1) || function () { alert('done');  }
    

The function declaration would be assigned in this case:

  • false || function (){ alert('done'); }
    

Note, that "complete" property would not hold a value, just a function definition, you would need to call complete as something like complete(). For the function to be called if the left side is false, you'd have to surround it in parentheses and call it:

  • complete: (i !== row * cols - 1) || (function () {alert('done');})()
    

Note: The left hand side will only be false if something is undefined (i think), or if i turns out to equal rows*cols -1.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号