我遇到了一段 javascript 的问题,当我不希望它评估为 true 时。当 indexOf 计算 rec.name - 等于“CSI”时 - 它返回 true 并触发 continue 行,因为 finalArr 数组包含一个名为“CSIQ Group”的元素。但是,这不是我想要的,因为我只希望它在数组中找到完全匹配的元素时评估为 true。
这是代码片段:
if(finalArr.join().indexOf(rec.name.toString()) > -1){
continue;
}
当“CSIQ Group”已经在finalArr中时,我可以改变什么来防止“CSI”触发继续线?谢谢!
亲切的问候, 约瑟夫
答案 0 :(得分:2)
您可以尝试使用 findIndexOf,或者在您的情况下仅 find 应该可以解决问题,甚至 includes。
像这样:
if(finalArr.includes(rec.name){
continue;
}
includes
非常适合简单的字符串匹配。如果您想要更大的匹配,那么您可以尝试find
。 find
可让您将数组中的每个元素与特定条件进行比较,并且您可以对其执行多项检查。
if(!!finalArr.find(element => (element.toLowerCase() === name.rec.toLowerCase()){
continue;
}
但是,我绝对建议不要将数组转换为字符串并尝试搜索它,尤其是在这种情况下。
答案 1 :(得分:0)
您可以使用 RegExp 将字符串与 CSI
完全匹配:
const pattern = /^CSI$/ // ^ - start of the string, $ - end of the string
pattern.test(rec.name.toString()) // true if only "CSI", false otherwise
如果找到单词 CSI
,您可以使用它来修改您的代码并执行您需要的操作。