我想在myArray中搜索“nana”,它应该返回“banana”元素的索引。
var myArray =["apple","banana","cherry"];
我该怎么做?
我有这个,但也许你有更聪明的方式
for(var i=0;i < myArray.length; i++){
if(myArray[i].indexOf("nana") !=-1) { return i; }
}
答案 0 :(得分:2)
如果ES6
不是问题,您可以使用array.prototype.findIndex
和string.prototype.includes
:
var myArray =["apple","banana","cherry"];
var search= "nana";
var index = myArray.findIndex(el => el.includes(search));
console.log(index);
&#13;
答案 1 :(得分:1)
使用findIndex
var input = "nana";
var output = myArray.findIndex( s => s.indexOf( input ) != -1 );
<强>演示强>
var myArray =["apple","banana","cherry"];
var input = "nana";
var output = myArray.findIndex( s => s.indexOf( input ) != -1 );
console.log(output);
&#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
强>
var myArray =["apple","banana","cherry"],
word= "nana";
console.log(myArray.findIndex( s => s.indexOf( word ) > -1 ))
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'));