三目运算符相信你们都很熟悉了:code
foo ? 'foo == true' : 'foo == false'
而三目运算符?:?:?.....
的调用方式你们也不陌生, 就至关于一堆if - else if语句:ip
foo ? 'foo == true' : bar ? 'bar == true' : 'bar == false'
可是在zepto.js里有一段代码:element
slice.call( isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all )
这里的三目运算符用的是??::
的形式,我搞不太懂,因此打算作个实验搞懂它:zepto
var bool1 = true, bool2 = true, val1 = 'val1', val2 = 'val2', val3 = 'val3'; console.log(bool1 ? bool2 ? val1 : val2 : val3);
用表格记录下4个不一样点状况:get
bool1 bool2 值 true true val1 true false val2 false true val3 false false val3
能够看出上面的代码等价于:it
console.log(bool1 ? ( bool2 ? val1 : val2 ) : val3);
条件(三元)运算符 -mdn上说三目运算符具备右结合性,根据以上两个例子,我总结三目运算符右结合性的意思是:io
好比:console
?:?:?:?:?:
能够取为class
?:(?:(?:(?:(?:))))
而select
???:::
能够取为
?(?(?:):):
而后根据你加上的括号,能够写出等价的if判断语句,这样就能理解复杂三目运算符所包含的意义了。
注意,三目运算符中"?"和":"是成对出现的,最起码数量上,有几个"?"就会有几个":".