gpt4 book ai didi

javascript - RegExp.test (JavaScript) 错误

转载 作者:搜寻专家 更新时间:2023-11-01 05:09:34 25 4
gpt4 key购买 nike

我在我的代码中发现了一个有趣的问题。 Here是我的代码的简化版本。每次调用 regex.test 都会更改其输出值。您可以尝试在 devtools 中使用“选择评估”来做到这一点,它会显示不同的值。

最佳答案

问题是您在 Regexp 中使用了 /g - 当使用它并且多次执行 regex 时,它总是会从上次停止的地方开始。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex

This property is set only if the regular expression instance used the "g" flag to indicate a global search. The following rules apply:

If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.

If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex.

If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.

Otherwise, lastIndex is set to the next position following the most recent match.

您可以通过在循环中执行 console.log(regex.lastIndex) 来验证这一点:

for (var a = 0; a < 10; a++) {
console.log(regex.lastIndex)
if (!regex.test(inner)) {
log.innerHTML += "true";
}
else {
log.innerHTML += "false";
}

log.innerHTML += " ";
}

你会看到它在 0 和 18 之间交替。所以,当它从 0 开始时,它匹配,当它从 18 开始时,它不匹配。

关于javascript - RegExp.test (JavaScript) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43827851/

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