[英]Confusion with Javascript Ternary Operator in Text Parsing Function
I am quite confused with the following snippet found in a findAndReplace
function: 我对在findAndReplace
函数中找到的以下代码片段感到很困惑:
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. 我认为三元运算符意味着,如果searchText
是字符串,则将创建regexp对象。 But it also appears that the variables childNodes
, cnLength
, and excludes
are being set irrespective of what type the searchText
is. 但它也出现了变量childNodes
, cnLength
,并且excludes
被设定不论什么类型的searchText
是。
I think I may just be quite confused about the syntax - but are lines 3 through 5 part of the conditional statement or separate? 我想我可能只是对语法感到困惑-但是条件语句的第3至5行是单独的还是单独的? 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. 第3至5行不是条件三元运算符的一部分。 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
'string' ? new RegExp(searchText, 'g') : searchText
is assigned to the first variable, regex
. 'string' ? new RegExp(searchText, 'g') : searchText
分配给第一个变量regex
。 The other variables are likewise assigned their own expressions. 其他变量同样分配有自己的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.