问题
What is the difference between these various uses of the "&&" logical operator?
From Oliver Steele's Functional.js library. Line 4, "args.length && arg":
0 Function.prototype.partial = function(){
1 var fn = this, args = Array.prototype.slice.call(arguments);
2 return function(){
3 var arg = 0;
4 for ( var i = 0; i < args.length && arg < arguments.length; i++ )
5 if ( args[i] === undefined )
6 args[i] = arguments[arg++];
7 return fn.apply(this, args);
8 };
9 };
From bootstrap.js. Line 11 below, "'hover' && this.$element":
1 var Carousel = function (element, options) {
2 this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
3 this.$indicators = this.$element.find('.carousel-indicators')
4 this.options = options
5 this.paused =
6 this.sliding =
7 this.interval =
8 this.$active =
9 this.$items = null
10
11 this.options.pause == 'hover' && this.$element
12 .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
13 .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
14 }
Also why not just use the + arithmetic operator in the first example?
Here is yet another example that I'm having trouble grokking, from the same Carousel section of bootstrap.js:
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
回答1:
Well, it's the same operator everywhere, but being used for different purposes by the programmer.
The first code example is not doing args.length && arg
at all, but is rather doing the equivalent of (i < args.length) && (arg < arguments.length)
because &&
has lower precedence than <
. It means, "loop until either i
is at or surpasses the argument count or arg
is at or surpasses the argument count". You can see that +
is therefore not equivalent in this context.
The other code examples are all exploiting the fact that the logical-and operator (&&
) "short-circuits" when its left-hand operand is false, i.e. it only evaluates the expression on the right if the one on the left is true.
So, this.options.pause == 'hover' && this.$element.on(...
is a short-hand way of attaching the event listeners only if the pause option is set to 'hover' (because if it's not, the left-hand expression will be false, and the on
functions won't be called).
Similarly, the final example you found only calls setInterval
(and assigns the result to this.interval
) if the desired interval is "true" (I imagine generally non-zero here, but also not undefined, etc.) and the carousel is not paused.
来源:https://stackoverflow.com/questions/25368314/whats-the-difference-between-these-two-uses-of-the-logical-operator