开发者

help me understand a variable setting

开发者 https://www.devze.com 2023-01-02 09:06 出处:网络
var fmt = document.documentElement.clientWidth; var开发者_JAVA百科 cls = (fmt<=240)?\'pda_ver\':(fmt>240&&fmt<=320)?\'pda_hor\':(fmt>320&&fmt<=640)?\'screen_ultralow\':(
var fmt = document.documentElement.clientWidth;
        var开发者_JAVA百科 cls = (fmt<=240)?'pda_ver':(fmt>240&&fmt<=320)?'pda_hor':(fmt>320&&fmt<=640)?'screen_ultralow':(fmt>640&&fmt<=800)?'screen_low':(fmt>800&&fmt<=1024)?'screen_med':(fmt>1024&&fmt<=1280)?'screen_high':'screen_wide';

can someone tell me what this does (just the part where the variable is set with a value. I do not understand... what are the ?, : have for a role here)? i have never seen a variable declared like that. Is this a conditional variable setting? if yes how does it work ?

working example


This is a horrible example of abuse of the ternary operator.

Using a switch statement would look much nicer.


This construction is somewhat common in languages:

statement3 ? statement2 : statement1

It is used to inline a conditional, and it reads:

if (statement3) {
  statement2;
} else {
  statement1;
}


It's a shorthand of:

var cls;
if (fmt <= 240) {
  cls = 'pda_ver';
} else {
 if (fmt > 240 && fmt <= 320) {
   cls = 'pda_hor';
 } else {
 ....

and so on

0

精彩评论

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

关注公众号