【问题标题】:Search Array Elements For Substring and return index [duplicate]搜索子字符串的数组元素并返回索引
【发布时间】:2021-09-27 12:08:41
【问题描述】:

我正在尝试搜索 Array 中的每个元素以查找它是否包含子字符串。如果是,我希望返回索引。

目前,我正在使用此代码:

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);

但不确定这是否是最好的方法。

【问题讨论】:

    标签: javascript html jquery arrays substring


    【解决方案1】:

    试试这个

    const arr = ["bbc_0","d","e","heat_","a","c"]
    const index = arr.findIndex(i => i.includes("heat"))
    console.log(index) //should be 3

    【讨论】:

    • 好点。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多