它在以下情况下不起作用:
function test(str) {
var vowelsCount = 0;
var arr = str.split('');
var regex = new RegExp(/[aeiou]/, 'gi');
arr.forEach((item, index, array) =>{
if(regex.test(item)){
vowelsCount++;
}
});
return vowelsCount;
}
test('pear tree'); //2,it passes a and the second e
它在以下情况下有效:
arr.forEach((item, index, array) =>{
var regex = new RegExp(/[aeiou]/, 'gi');
if(regex.test(item)){
vowelsCount++;
}
});
为什么正则表达式对象在循环外赋值时不正确?
最佳答案
因为你使用了g
标志。删除全局标志,它将起作用。原因是当您在 regex
变量中使用 g
标志时,您有 lastIndex
字段。当您在不同的数组字符串上使用 regex
时,该索引包含不正确的值。在第二个示例中,您可以在每次迭代中定义新的 regex
并且 lastIndex
字段每次都设置为 0。您也可以手动重置该索引。
function test(str) {
var vowelsCount = 0;
var arr = str.split('');
var regex = new RegExp(/[aeiou]/, 'gi');
arr.forEach((item, index, array) =>{
if(regex.test(item)){
vowelsCount++;
}
regex.lastIndex = 0
});
return vowelsCount;
}
test('pear tree');
关于javascript - 为什么正则表达式对象在 "for"循环之外分配时不起作用?JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504995/