发布于 2015-07-04 17:54:47
.exec()
是一种正则表达式方法:
exec()方法在指定的字符串中执行匹配搜索。返回结果数组,或null。
这里是||
如何工作
此方法返回的结果要么是数组,要么是null
。如果返回一个数组,则["", ""]
部件将被丢弃,其结果数组将用于表达式的其余部分。否则,生成的null
将被丢弃,表达式的其余部分将使用["", ""]
。
例如,假设rtagName.exec(elem)
返回:
["we", "Quir", "idid"]
那么表达式的结果将是:
(["we", "Quir", "idid"] || ["", ""])[1].toLowerCase()
(["we", "Quir", "idid"])[1].toLowerCase()
"Quir".toLowerCase()
"quir" //final result
否则,最终结果将是"":
(null || ["", ""])[1].toLowerCase()
(["",""])[1].toLowerCase()
"".toLowerCase()
"" //final result
以下是简单的对等词:
var x = rtagName.exec(elem);
var tag;
if( x ) {
tag = x[1].toLowerCase();
} else {
tag = "";
}
如果没有|| ["",""]
,您就有可能得到(null)[1].toLowerCase()
,它会抛出一个错误,这会导致代码失败。由于.exec()
方法主要涉及搜索字符串以寻找匹配,所以要么找到匹配,要么找不到;["", ""]
允许您返回"“(空字符串) --而不是抛出错误--当没有找到匹配时。
https://stackoverflow.com/questions/31226548
复制相似问题