查找数组中项目包含子字符串的索引
Find the index of item in array where the item contains a substring
我正在用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, "<").replace(/>/g, ">"); //result
我确实想知道为什么您将 html 存储在数组中。为什么不在数组中存储引用并使用 HTML 模板用正确的数据填充它。
找到了一种更简单的方法,只需将 html 中的字符串连接到变量中,然后将其作为 innerHTML 附加到 domnode 中。比循环、创建和追加要快得多。;-)
对于u_number的选择,我发现它是一个属于客户端的静态数字,因此选择很容易。
不过谢谢你的帮助。
相关文章:
- AngularJS-ng使用字符串索引在数组上重复
- 在 JavaScript 中动态创建带有字符串索引的二维表
- 按字符串索引的 Javascript 数组
- 按字符串索引访问字典对象
- 每个和字符串索引
- 使用字符串中的开始和结束单词以及 javascript 中的子字符串索引查找子字符串
- JavaScript 数组中的字符串索引
- 如何从数组中删除特定元素?与字符串索引
- Why for var在数组中返回一个字符串索引
- 为什么数组中的字符串索引不会增加'长度'
- 字符插入错误的字符串索引
- Javascript字符串索引
- 如何在不计算扩展实体的情况下找到标记(元素)的字符串索引?
- 如何忽略字符串索引中的空格,并在句子中的每个单词上以大写字母开头
- Jquery的每个函数都不能用于字符串索引数组
- 为什么IE's插入符在文本输入中的位置不等于字符串索引?解决方法是什么?
- 字符串索引器在本地工作,但在网站托管时不起作用
- 在Javascript中迭代由字符串索引的数组
- 在javascript中创建两个数组的字符串索引对象
- 如何创建具有字符串索引的二维对象并循环遍历结果