我很困惑这怎么可能......
var matcher = new RegExp("d", "gi");
matcher.test(item)
上面的代码包含以下值
item = "Douglas Enas"
matcher = /d/gi
然而,当我背靠背运行 matcher.test 函数时,我在第一次运行时得到 true,在第二次运行时得到 false。
matcher.test(item) // true
matcher.test(item) // false
如果我使用正则表达式文字,例如
/d/gi.test("Douglas Enas")
并在chrome中背靠背运行它两次我都得到了真实的结果。对此有解释吗?
在 chrome 控制台中使用构造函数创建正则表达式对象的背靠背运行示例
matcher = new RegExp("d","gi")
/d/gi
matcher.test("Douglas Enas")
true
matcher.test("Douglas Enas")
false
matcher
/d/gi
在文字上使用背靠背调用的示例
/d/gi.test("Douglas Enas")
true
/d/gi.test("Douglas Enas")
true
这个问题的原因是因为使用 RegExp 构造函数和针对值列表的测试函数我失去了匹配......但是使用文字我得到了我期望的所有值
更新
var suggestions = [];
////process response
$.each(responseData, function (i, val)
{
suggestions.push(val.desc);
});
var arr = $.grep(suggestions, function(item) {
var matcher = new RegExp("d", "gi");
return matcher.test(item);
});
在闭包内移动匹配器的创建包括丢失的结果。“d”实际上是一个动态创建的字符串,但为了简单起见,我使用了“d”。我仍然不确定现在每次进行测试时创建一个新表达式,当我迭代建议数组时会无意中排除结果仍然有点令人困惑,并且可能与匹配测试的进步有关