.match()只匹配相同字符串数组中的一部分



我正在用正则表达式匹配字符串数组:

for (let subject_index in subjects) {
if (subjects[subject_index].match(/.*Overview of Investor.*/i)) {
subjects.splice(subject_index, 1)
}
}

数组subjects包含9个相同的字符串,它们都是Overview of Investor。当我运行这个循环时,它正确匹配了五个字符串,而不匹配其他四个字符串,即使所有的字符串都是相同的。我错过什么了吗?

在迭代数组的同时编辑它,这可能会导致奇怪的问题。您可以使用Array.filter.

以更好的方式完成此操作。
subjects = subjects.filter(subject => !subject.match(/.*Overview of Investor.*/i));

这样,你就不会在读取元素的同时编辑数组。

编辑:正如评论中所指出的,这个解决方案删除了匹配的字符串,因为这是原始海报的解决方案试图做的。如果希望保留匹配的字符串,请使用

subjects = subjects.filter(subject => subject.match(/.*Overview of Investor.*/i));

这是相同的代码,但没有感叹号。

不要在循环中改变数组。创建一个新的数组来添加匹配项。

let subjects = ["Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor"];
let ans = [];
for (let subject_index in subjects) {
if (subjects[subject_index].match(/.*Overview of Investor.*/i)) {
ans.push(subjects[subject_index]);
}
}