在javascript中,如何在数组中搜索子字符串匹配 [英] In javascript, how do you search an array for a substring match
问题描述
我需要在 javascript 中搜索一个数组.搜索将仅匹配字符串的一部分,因为该字符串将分配有附加编号.然后我需要用完整的字符串返回成功匹配的数组元素.
I need to search an array in javascript. The search would be for only part of the string to match as the string would have addtional numbers assigned to it. I would then need to return the successfully matched array element with the full string.
即
var windowArray = new Array ("item","thing","id-3-text","class");
我需要搜索包含 "id-"
的数组元素,我还需要提取元素中的其余文本(即 "id-3-text"
).
I need to search for the array element with "id-"
in it and i need to pull the rest of the text in the element as well (ie. "id-3-text"
).
谢谢
推荐答案
在你的具体情况下,你可以用一个无聊的旧计数器来做:
In your specific case, you can do it just with a boring old counter:
var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
value = windowArray[index];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
// Use `result` here, it will be `undefined` if not found
但如果你的数组是sparse,你可以做到使用适当设计的 for..in
循环更有效:
But if your array is sparse, you can do it more efficiently with a properly-designed for..in
loop:
var key, value, result;
for (key in windowArray) {
if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = windowArray[key];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
}
// Use `result` here, it will be `undefined` if not found
注意没有 hasOwnProperty
和 !isNaN(parseInt(key, 10))
检查的幼稚 for..in
循环;原因.
Beware naive for..in
loops that don't have the hasOwnProperty
and !isNaN(parseInt(key, 10))
checks; here's why.
离题:
另一种写法
var windowArray = new Array ("item","thing","id-3-text","class");
是
var windowArray = ["item","thing","id-3-text","class"];
...这对你来说打字更少,也许(这一点是主观的)更容易阅读.这两个语句的结果完全相同:一个包含这些内容的新数组.
...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.
这篇关于在javascript中,如何在数组中搜索子字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!