Javascript Array.find方法有时返回项目,有时未定义

我有一个看起来像这样的数组:

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 calls i[1].test(...) on odd iterations, matching against "github" in "github.com", and advancing lastIndex. Then, on the next even iteration, the next call to test 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文档:

    与exec()(或与其结合使用)一样,在同一全局正则表达式实例上多次调用的test()将前进到先前的匹配。

    (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)