javascript - 在 Sizzle(CSS 选择器引擎)中解释一段疯狂的 JS 代码

标签 javascript regex sizzle

因此,这是预过滤“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;
}

代码摘自line 442-458 of sizzle.js .

那么,为什么 var test = ... 行让 exec 输入一个 bool 值?或者那真的是一个字符串?

有人能把它分成几行代码来解释吗?

最佳答案

exec 方法将接收一个字符串,因为 Boolean Logical Operators可以返回一个操作数,不一定是 Boolean 结果,例如:

逻辑与运算符(&&)将返回第二个操作数的值,如果第一个真值 em>:

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

如果它本身falsy,它将返回第一个操作数的值:

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

逻辑 OR 运算符 (||) 将返回第二个操作数的值,如果第一个操作数:

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

如果它本身非假,它将返回第一个操作数的值:

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

Falsy 值为:nullundefinedNaN0、零长度字符串,当然还有 false

在 bool 上下文中评估的任何其他内容都是 truthy(将强制转换为 true)。

那么,让我们看一下表达式:

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
 );

关于javascript - 在 Sizzle(CSS 选择器引擎)中解释一段疯狂的 JS 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2528611/

相关文章:

javascript - 在GA中跟踪您网页的iframe嵌入

javascript - 加载后获取 Highcharts 系列数据

javascript - this.form.get 不是一个函数吗?

css - Sizzle 选择器引擎有什么用?

JavaScript - 单击事件时遇到问题

JavaScript:SplitAtFirst (':')

c# - 如何使正则表达式适用于角落案例电子邮件地址

Python正则表达式负向后查找,包括行首

正则表达式 - 匹配大写字母,特定字符后的简单字符串

jquery - 在 Sizzle/jQuery 中选择 Id 带有冒号的元素