简体   繁体   中英

Confusion with Javascript Ternary Operator in Text Parsing Function

I am quite confused with the following snippet found in a findAndReplace function:

var regex = typeof searchText === 'string' ?
            new RegExp(searchText, 'g') : searchText,
       childNodes = (searchNode || document.body).childNodes,
       cnLength = childNodes.length,
       excludes = 'html,head,style,title,link,meta,script,object,iframe';

I thought the ternary operator implied that if the searchText is a string, then the regexp object is created. But it also appears that the variables childNodes , cnLength , and excludes are being set irrespective of what type the searchText is.

I think I may just be quite confused about the syntax - but are lines 3 through 5 part of the conditional statement or separate? If they are separate, why is there no semicolon at the end of line 2?

Lines 3 through 5 are not part of the conditional ternary operator. The commas are used to declare separate variables, not related to each other. The following is valid syntax:

var a = 1, b = 2, c = "apples";

In this case, 'string' ? new RegExp(searchText, 'g') : searchText 'string' ? new RegExp(searchText, 'g') : searchText is assigned to the first variable, regex . The other variables are likewise assigned their own expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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