开发者

Explain a block of crazy JS code inside Sizzle(the CSS selector engine)

So, here is the function for pre-filtering "CHILD":

function(match){
    if ( match[1] === "nth" ) {
        // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
        var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
            match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
            !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

        // calculate the numbers (first)n+(last) including if they are negative
        match[2] = (test[1] + (test[2] || 1)) - 0;
        match[3] = test[3] - 0;
    }

    // TODO: Move to normal caching system
    match[0] = done++;

    return match;
}

The code is extracted from line 442-458 of sizzle.js.

So, why is the line var test = ..., have the开发者_如何学运维 exec inputing a boolean? Or is that really a string?

Can someone explain it by splitting it into a few more lines of code?


The exec method will receive a string, because the Boolean Logical Operators can return an operand, and not necessarily a Boolean result, for example:

The Logical AND operator (&&), will return the value of the second operand if the first is truthy:

true && "foo"; // "foo"

And it will return the value of the first operand if it is by itself falsy:

NaN && "anything"; // NaN
0 && "anything";   // 0

The Logical OR operator (||) will return the value of the second operand, if the first one is falsy:

false || "bar"; // "bar"

And it will return the value of the first operand if it is by itself non-falsy:

"foo" || "anything"; // "foo"

Falsy values are: null, undefined, NaN, 0, zero-length string, and of course false.

Anything else, evaluated in boolean context is truthy (will coerce to true).

So, let's look the expression:

var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
  match[2] === "even" && "2n" ||  // return '2n' if match[2] is 'even'
  match[2] === "odd" && "2n+1" || // return '2n+1' if it's 'odd'
  !/\D/.test(match[2]) && "0n+" + match[2]|| // return '0n+N' if it's a digit(N) 
  match[2]  // otherwise, return the match[2] value
 );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜