我有一个看起来像这样的数组:
const list = [["GET", /github/g]];
它是一个带有子数组的数组,索引0具有字符串,索引1具有正则表达式。
我正在尝试做这样的事情:
function checkList() {
return list.find(i => i[0] === "GET" && i[1].test("github.com"));
}
Which I would expect to return the list it finds every time, but that's not the case, it flips back and forth from returning the list and returning undefined
.
这是一个例子:
let i = 1;
const list = [["GET", /github/g]];
while (i <=10) {
console.log(list.find(i => i[0] === "GET" && i[1].test("github.com")))
i++
}
In this example I just loop through it and log the results to show that it returns the list and undefined
every other time. What's going on here?
This is happening because the RegExp in
i[1]
is actually stateful. Your code callsi[1].test(...)
on odd iterations, matching against"github"
in"github.com"
, and advancinglastIndex
. Then, on the next even iteration, the next call totest
fails to find another match, reaching the end of the string. After that, the RegExp restarts the search from the beginning of the string.If you would just like to check whether the pattern is found at least once, you could simply remove the
/g
flag at the end.来自MDN文档:
(See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)