And*_* Li 3 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;
}
Run Code Online (Sandbox Code Playgroud)
该代码是从sizzle.js的442-458行中提取的.
那么,为什么这行var test = ...,让exec输入一个布尔值?或者这真的是一个字符串?
有人可以通过将其分成几行代码来解释它吗?
CMS*_*CMS 10
该exec方法将接收一个字符串,因为布尔逻辑运算符可以返回一个操作数,而不一定是Boolean结果,例如:
该逻辑与运算符(&&),将返回的值,第二个操作数,如果第一个是truthy:
true && "foo"; // "foo"
Run Code Online (Sandbox Code Playgroud)
并且它将返回第一个操作数的值,如果它本身是假的:
NaN && "anything"; // NaN
0 && "anything"; // 0
Run Code Online (Sandbox Code Playgroud)
的逻辑OR运算符(||)将返回所述第二操作数的值,如果第一个是falsy:
false || "bar"; // "bar"
Run Code Online (Sandbox Code Playgroud)
并且它将返回第一个操作数的值,如果它本身是非虚假的:
"foo" || "anything"; // "foo"
Run Code Online (Sandbox Code Playgroud)
Falsy值是:null,undefined,NaN,0,零长度的字符串,当然false.
在布尔上下文中评估的任何其他内容都是真实的(将强制执行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
);
Run Code Online (Sandbox Code Playgroud)