admin管理员组文章数量:1356032
I am practicing this Clock tutorial.
Everything in the code is clear to me.
Accept this hr = hr>=12 ? hr-12 : hr;
is not clear me. May be it's a if else
statement.
Can any explain what this code is doing?
Thanks :)
I am practicing this https://developer.mozilla/en/Canvas_tutorial/Basic_animations Clock tutorial.
Everything in the code is clear to me.
Accept this hr = hr>=12 ? hr-12 : hr;
is not clear me. May be it's a if else
statement.
Can any explain what this code is doing?
Thanks :)
Share Improve this question edited Jan 16, 2020 at 6:20 sandeep asked Jun 15, 2012 at 6:30 sandeepsandeep 92.9k24 gold badges140 silver badges156 bronze badges8 Answers
Reset to default 4This is the ternary operator (?:)
Here is the simple explanation of what is being done here:
if(hr>=12)
{
hr=hr-12;
}
//or else hr will have its same value
if (hr >= 12) {
hr = hr - 12;
}
if hr
does not meet that criteria hr
should effectively be left untouched.
its called Ternary operation
It means
if(hr>=12)
hr=hr-12;
else
hr=hr;
the following is enough
if(hr>=12)
hr=hr-12;
It's a ternary operator, of the form:
condition ? if_true | if_false
If you add more brackets for readibility, it can bee:
hr = ( (hr >= 12) ? (hr - 12) : hr )
That is, if more than 12, subtract 12, and store back to hr.
hr= hr>=12 ? hr-12 : hr;
is same to if( hr >= 12 ) hr = hr-12 else hr = hr;
the bool ? expr_a : expr_b
is a operator that when bool
is true, expr_a is evaluated and its value will be used as the whole expr's value, otherwise the expr_b will be.
It means:
if(hr>=12)
{
hr = hr - 12;
}
Generally:
x= condition ? y : z
if condition is true, then x = y
, else x = z
It has same effect as this:
hr %= 12; //equivalent to -> hr = hr>=12 ? hr-12 : hr;
It's called a ternary operator.
本文标签:
版权声明:本文标题:javascript - What is this hr = hr>=12 ? hr-12 : hr; means? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743960696a2568969.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论