在写代码的过程中过多的使用if else会使代码看上去很拖沓,这个时候我们可以用三元运算符来替代,会使我们的代码更简洁。
用法实例:flag?a:b;
flag即为判断条件,判断结果为Boolean型,为true时,调用结果为a;为false时,调用结果为b。简单来说就是如果判断为真执行a,否则执行b。
?运算符可以用作if...else的快捷方式。
例:
如果使用if...else
var a = 5; var b; if (a==5) { b=true; }else{ b=false; }
如果使用三元运算符
var a = 5; var b; (a==5)?b="true":b="false";
两种写法最后b的值均为true;
在一般情况中我们会遇到更为复杂的判断,例如在jquery中,使用if...else
if($('.class').hasClass('active')){ $('body').addClass('color'); }else{ $('body').removeClass('color'); }
使用三元运算符
$('.class').hasClass('active')?$('body').addClass('color'):$('body').removeClass('color');
或者可以改写成:
$('body')[$('.class').hasClass('active')?'addClass':'removeClass']('color');
当然三元运算符还有更广泛的使用,以上只是简单地示范三元运算符的操作。我们在以后的编码中可以活用三元运算来使我们的代码更简洁。