查找数组中项目包含子字符串的索引

Find the index of item in array where the item contains a substring

本文关键字:字符串 索引 包含 数组 项目 查找      更新时间:2023-09-26

我正在用javascript动态编写html并将其存储在数组中。

["<div id="findme_u_13" name="someone" ><span style="… id="null" width="15px" height="15px"/></a></div>", "<div id="findme_u_1106" name="anotherone" ><span s… id="null" width="15px" height="15px"/></a></div>"]

之后,我希望能够确定包含 ie findme_u_somenumber的完整项目的索引。

我已经查看了 indexof 方法,但这显然不起作用。我想存储 html 的原因是加快附加到 Dom 的速度,并一遍又一遍地跳过创建 Html。有没有一种快速的方法可以在数组中搜索 ie 1000 个字符串并返回包含该值的字符串的索引?

indexOf确实有效。我认为问题是当您应该使用单引号时,您使用双引号来分隔元素(因为 HTML 中的双引号)。这将返回索引或 false。

function findThis(arr, id) {
    for (var i = 0, len = arr.length; i < len; i++) {
       if (arr[i].indexOf(id) > -1) return i;
    }
    return false
}
findThis(arr, 'findme_u_1106') // 1

演示

您可以将 HTML 放在数组中的node中,并使用查询选择器将其取出。这样,您就可以遍历内存中的那位 HTML。这给出了以下问题的解决方案:

var html_array = ['<div id="findme_u_13" name="someone" ><span id="null" width="15px" height="15px"></span></div>', '<div id="findme_u_1106" name="anotherone" ><span id="null" width="15px" height="15px"></span></div>'];
function retrieveIndexFromArray(indexNumber)
{
  var elementFound = -1; //
     var div = document.createElement("div"); //create an in-memory node.
     div.innerHTML = html_array.join(""); //add the string to it.
     var element = div.querySelector("#findme_u_"+indexNumber)
     if (element) //test if the string matches the index requested.
     {
         elementFound = element; //save the element
     }
console.log(element)
  return element; //return the element;
}
document.body.innerHTML += "Found element: " + retrieveIndexFromArray(13).outerHTML.replace(/</g, "&lt;").replace(/>/g, "&gt;"); //result

我确实想知道为什么您将 html 存储在数组中。为什么不在数组中存储引用并使用 HTML 模板用正确的数据填充它。

找到了一种更简单的方法,只需将 html 中的字符串连接到变量中,然后将其作为 innerHTML 附加到 domnode 中。比循环、创建和追加要快得多。;-)

对于u_number的选择,我发现它是一个属于客户端的静态数字,因此选择很容易。

不过谢谢你的帮助。