gpt4 book ai didi

javascript - RegExp 构造函数和 Regex 文字测试函数之间的区别?

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:47 24 4
gpt4 key购买 nike

<分区>

我对这怎么可能感到困惑......

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”。我仍然不确定现在每次我在迭代建议数组时创建一个新表达式会无意中排除结果仍然有点令人困惑,并且可能与匹配测试的进步有关

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com