问题
In the following code
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
the part '$active.next().length' doesn't seem to compare anything and I don't understand how the condition is determined to be True or False.
Or is it saying that: if the various $next is equal to $active.next().length then the condition is true?
回答1:
In javascript any expression can be converted to a truthy or falsy value and hence is valid in a comparison place. The values which are false in javascript are
false
0
""
(empty string)null
undefined
NaN
In this case length
refers to a numeric value and if it evaluates to 0
then it will be considered falsy. Otherwise it will be truthy
回答2:
If the length
property is equal to 0
or undefined
(i.e. $active
is not an array), the condition will be false
.
回答3:
If $active.next().length
is true
, which means that there is a next element, then $next = $active.next()
. Otherwise $next = $('#slideshow IMG:first')
. The ?
operator is called the ternary operator. It is a short if else
.
回答4:
It's a ternary comparison equivalent to:
if($active.next().length) {
$next = $active.next();
}
else {
$next = $('#slideshow IMG:first');
}
So the condition is based on $active.next().length which should return a value of zero or greater. Anything greater than zero, JavaScript will interpret as true, zero false.
回答5:
What you're looking at a Ternary opertation which is a short hand for If... Else... has you mentioned in the title.
So the long version of your statement is;
if($active.next().length){
$next = $active.next();
}else {
$next = $('#slideshow IMG:first');
}
来源:https://stackoverflow.com/questions/10401297/why-is-there-no-comparison-statement-in-this-javascript-if-else-statemen