有谁知道在不使用indexOf的情况下检查列表是否包含字符串的方法?在我的数组中,有些字符串可以包含其他字符串的一部分,因此indexOf将产生假阳性。
例如,如何确定“组件”是否在下面的数组中?
["component.part", "random-component", "prefix-component-name", "component"]
更新:
看来我的假阳性是误导性的。我的意思是,当我想要自己匹配字符串时,它会说组件在那里4次。
即。当检查下面数组中是否存在"component“时,它应该返回false。
["component.part", "random-component", "prefix-component-name"]
发布于 2016-08-07 20:15:23
使用Array.find
API。
示例:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
有关更多用法的示例。
发布于 2016-08-07 20:15:06
一种方法是使用.find()
从数组中获取所需的字符串。
发布于 2016-08-07 20:22:47
尝试使用$.inArray()方法。
var list=["component.part", "random-component", "prefix-component-name", "component"];
if($.inArray(" component",list) != -1){
console.log("Item found");
}
https://stackoverflow.com/questions/38821177
复制