为什么这个分号会导致错误的错误结果
Why does this semi-colon cause a incorrect falsey result
奇怪的真相测试结果
filter = /rob/gi
>> /rob/gi
filter.test('hey')
>> false
filter.test('rob')
>> true
true && filter.test('rob');
>> false
true && filter.test('rob') ;
>> true
(true && filter.test('rob'));
>> false
(true && filter.test('rob')) ;
>> true
可在 Firefox 和 Chrome
中重现
那是因为 .test
的行为与 .exec()
相同,并且在调用之间保持状态(位置)
As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.
所以对于 'rob'
输入它匹配它。然后在第二次调用时,它会尝试匹配第一次匹配后剩下的任何内容:它是一个空字符串,因此它会失败并倒带。
要查看它的实际效果,请尝试匹配 'robrobrob'
- 将有 3 个 true
,然后是 false
。
参考文献:
UPD:
- 在这种特殊情况下,它的发生是因为您使用了
g
修改(记入 Barmar)
奇怪的真相测试结果
filter = /rob/gi
>> /rob/gi
filter.test('hey')
>> false
filter.test('rob')
>> true
true && filter.test('rob');
>> false
true && filter.test('rob') ;
>> true
(true && filter.test('rob'));
>> false
(true && filter.test('rob')) ;
>> true
可在 Firefox 和 Chrome
中重现那是因为 .test
的行为与 .exec()
相同,并且在调用之间保持状态(位置)
As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.
所以对于 'rob'
输入它匹配它。然后在第二次调用时,它会尝试匹配第一次匹配后剩下的任何内容:它是一个空字符串,因此它会失败并倒带。
要查看它的实际效果,请尝试匹配 'robrobrob'
- 将有 3 个 true
,然后是 false
。
参考文献:
UPD:
- 在这种特殊情况下,它的发生是因为您使用了
g
修改(记入 Barmar)