我正在尝试搜索数组中的每个元素以查找它是否包含子字符串。如果确实如此,我希望返回索引。
目前,我正在使用此代码:
function searchString(){
for(n=0; n<a0.length; n++){
if(a0[n].substring(0,4)=="heat"){
return n;
}
};
}
a0 = new Array("bbc_0","d","e","heat_","a","c");
a2 = searchString();
alert("heat APPEARS @ index: "+a2);
但不确定这是否是最好的方法。
答案 0 :(得分:1)
试试这个
const arr = ["bbc_0","d","e","heat_","a","c"]
const index = arr.findIndex(i => i.includes("heat"))
console.log(index) //should be 3