Google Apps Script中使用Array.indexOf()正则匹配失败问题求助
问题根因
Array.indexOf() 执行的是严格相等匹配(===),你传入的参数是正则对象,而数组元素为字符串,二者类型完全不同,永远无法匹配成功,和字符串内是否包含空格没有关联,属于方法使用逻辑错误。
修正方案
遍历数组对每个元素单独执行正则匹配,收集符合条件的索引即可,参考代码如下:
function setContactTypes(){ // 匹配规则 const contactRegExp = /contact \d* Type/i; const headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type']; const hitArray = []; headerIndexList.forEach((item, index) => { if (contactRegExp.test(item)) { hitArray.push(index); } }); // 最终hitArray值符合预期为 [1, 3] }
如果需要保留你原有的从指定位置循环查找的逻辑,可自定义正则匹配的索引查找方法:
function regexIndexOf(arr, regex, startPos = 0) { for (let i = startPos; i < arr.length; i++) { if (regex.test(arr[i])) return i; } return -1; } // 原循环逻辑调整为 let i = -1; while ((i = regexIndexOf(headerIndexList, contactRegExp, i + 1)) !== -1) { hitArray.push(i); }
内容的提问来源于stack exchange,提问作者ThePirate
相关产品推荐
相关产品推荐

