2016-08-08 59 views
1

有谁知道一种方法来检查列表是否包含一个字符串而不使用indexOf?在我的数组中,一些字符串可能包含其他字符的一部分,所以indexOf会产生误报。Javascript列表包含字符串

作为一个例子,我将如何确定“component”是否在下面的数组中?

["component.part", "random-component", "prefix-component-name", "component"] 

更新:

好像我用假阳性的是误导。我的意思是说,当我想自己匹配字符串时,组件会在那里出现4次。

即。在检查下面数组中是否存在“组件”时它应该返回false。

["component.part", "random-component", "prefix-component-name"] 
+1

的IndexOf不会给你假阳性。它会给你3.如果你想找到所有具有“otherstuffcomponent”的元素,你可以遍历你的数组并查看'String.includes()' –

回答

3

使用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."); 
 
}

有关详细的使用示例。

参见: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

+0

我想他想找到所有包含“component”的元素。 –

+0

@YasinYaqoobi这个问题有点不清楚,它听起来像是要求搜索错误中包含单词组件的项目。我已经包含了另一个解决方案。见下文。 –

+0

我显然让自己不清楚,我只想匹配确切的字符串“组件”。该示例旨在说明为什么我不能只使用indexOf。 – annedroiid

2

一种方法是使用.find()从数组中获取所需的字符串。

1

尝试使用$ .inArray()方法。

var list=["component.part", "random-component", "prefix-component-name", "component"]; 
if($.inArray(" component",list) != -1){ 
    console.log("Item found"); 
} 
0

有谁知道的方法来检查,如果列表中包含不使用的indexOf一个字符串?在我的数组中,一些字符串可能包含其他字符的一部分,所以indexOf会产生误报。

误报? Array.prototype.indexOfArray.prototype.includes都使用严格平等这使得在这里不可能。

-1

IndexOf不会给你误报。它会给你3.如果你想找到所有具有“otherstuffcomponent”的元素,你可以遍历你的数组,并检查与String.includes()

这是一个初学者友好的解决方案。

var arr = ["component.part", "random-component", 
 
    "prefix-component-name", "component", "asdf"]; 
 
    
 
    console.log(arr.indexOf('component')); // give u 3 
 
    
 
    for (var i = 0; i < arr.length; i++){ 
 
     if (arr[i].includes('component')){ 
 
     console.log(arr[i]); 
 
     } 
 
    }