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


const list = [["GET", /github/g]];



function checkList() {
    return list.find(i => i[0] === "GET" && i[1].test(""));

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("")))

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 "", 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.