[英]Why regex object doesn't work when it be assigned outside of the “for” loop?JavaScript
它在以下情况下不起作用:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.