简体   繁体   English

JavaScript如何解析链式三元表达式?

[英]How does JavaScript parse chained ternary expressions?

I'm reading through the jQuery source code for jQuery.filter and I stumbled upon this heaping pile of 我正在阅读jQuery.filter的jQuery 源代码,偶然发现了这堆

jQuery.filter = function( expr, elems, not ) {
    var elem = elems[ 0 ];

    if ( not ) {
        expr = ":not(" + expr + ")";
    }

    return elems.length === 1 && elem.nodeType === 1 ?
        jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
        jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
            return elem.nodeType === 1;
        }));
};

So in short we have 简而言之,我们有

return "a" && "b" ? "c" ? "d" : "e" : "f";

where each string could be a varying value 每个字符串可能是一个变化的值

My question isn't how to decipher this code, but my brain is tying in knots trying to evaluate the logic being used here. 我的问题不是如何解密此代码,但我的大脑在打结,试图评估此处使用的逻辑。

Can anyone help me understand how JavaScript evaluates this return expression? 谁能帮助我了解JavaScript如何评估此返回表达式?

The conditional operator is right-associative and the logical operators have higher precedence, so this: 条件运算符是右关联的,逻辑运算符具有更高的优先级,因此:

return "a" && "b" ? "c" ? "d" : "e" : "f";

Is equivalent to this: 等效于此:

return ( ("a" && "b") ? ("c" ? "d" : "e") : "f" );

Or in full: 或全部:

if ("a" && "b") {
    if ("c") {
        return "d";
    } else {
        return "e";
    }
} else {
    return "f";
}

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM