Why is there no comparison statement in this javascript 'If… Else…' statement

耗尽温柔 提交于 2019-12-07 05:46:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!