查找包含给定字符串部分

时间:2018-01-29 14:23:13

标签: javascript arrays search

我想在myArray中搜索“nana”,它应该返回“banana”元素的索引。

var myArray =["apple","banana","cherry"];

我该怎么做?

我有这个,但也许你有更聪明的方式

for(var i=0;i < myArray.length; i++){

    if(myArray[i].indexOf("nana") !=-1) { return i; }

}

4 个答案:

答案 0 :(得分:2)

如果ES6不是问题,您可以使用array.prototype.findIndexstring.prototype.includes

&#13;
&#13;
var myArray =["apple","banana","cherry"];
var search= "nana";
var index = myArray.findIndex(el => el.includes(search));
console.log(index);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用findIndex

var input = "nana";
var output = myArray.findIndex( s => s.indexOf( input ) != -1 ); 

<强>演示

&#13;
&#13;
var myArray =["apple","banana","cherry"];
var input = "nana";
var output = myArray.findIndex( s => s.indexOf( input ) != -1 );
console.log(output);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

所有浏览器都支持以下代码:

for + indexOf

var myArray =["apple","banana","cherry"],
    word= "nana";

for(var i=0; i <= myArray.length; i++){
    if(myArray[i].indexOf(word)>-1)
    {
       console.log(i)
       break;
    }
}

findIndex

您也可以使用findIndex,以下浏览器支持: enter image description here

var myArray =["apple","banana","cherry"],
    word= "nana";
console.log(myArray.findIndex( s => s.indexOf( word ) > -1 ))

jQuery»检查grep + indexOf是否存在:

var myArray =["apple","banana","cherry"],
    word= "nana";
    
var item = jQuery.grep(myArray, function( a ,i ) {
  if (a.indexOf(word)>-1)
  {
     console.log(i); 
     return a;
  }
})[0];

console.log("Is Exists: " + item!=undefined);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 3 :(得分:0)

您可能有多个与该搜索条件匹配的元素,在这种情况下,您可以使用reduce来捕获它们。

var myArray = ['apple', 'banana', 'cherry', 'fenana'];

function finder(arr, str) {
  return arr.reduce((p, c, i) => {
    if (c.includes(str)) p.push(i);
    return p;
  }, []);
}

console.log(finder(myArray, 'nana'));