我需要在javascript中搜索数组。搜索将只搜索要匹配的字符串的一部分,因为该字符串将具有分配给它的附加数字。然后,我需要返回匹配成功的数组元素和完整的字符串。
即
var windowArray = new Array ("item","thing","id-3-text","class");
我需要搜索包含"id-"
的数组元素,还需要提取元素中的其余文本(即,."id-3-text"
)。
谢谢
发布于 2010-12-30 01:08:25
在您的特定情况下,您可以只使用一个无聊的旧计数器:
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
但是,如果您的数组是,则可以使用设计得当的for..in
循环来更有效地执行此操作:
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
循环;here's why。
离题
另一种编写方式
var windowArray = new Array ("item","thing","id-3-text","class");
是
var windowArray = ["item","thing","id-3-text","class"];
...which为您减少了输入,也许(这一点是主观的)更容易阅读。这两条语句的结果完全相同:一个包含这些内容的新数组。
发布于 2012-10-26 07:45:44
如果您能够在项目中使用Underscore.js,那么数组函数可以让您轻松实现这一点:
// find all strings in array containing 'thi'
var matches = _.filter(
[ 'item 1', 'thing', 'id-3-text', 'class' ],
function( s ) { return s.indexOf( 'thi' ) !== -1; }
);
迭代器函数可以做任何您想做的事情,只要它为匹配返回true即可。效果很好。
更新2017-12-03:
现在,这是一个相当过时的答案。在大型批处理中可能不是性能最好的选项,但它现在可以编写得更简洁,并使用.filter()
和.includes()
等原生ES6数组/字符串方法:
// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));
注意:没有<= IE11对String.prototype.includes()
的支持(请注意,边缘工作),但您可以使用polyfill,或者直接退回到indexOf()
。
发布于 2018-09-01 09:36:20
这里的人把这件事搞得太难了。只需执行以下操作...
myArray.findIndex(element => element.includes("substring"))
findIndex()是一个ES6高阶方法,它遍历数组的元素,并返回符合某些条件的第一个元素的索引(作为函数提供)。在本例中,我使用ES6语法来声明高阶函数。element
是函数的参数(可以是任何名称),胖箭头将后面的内容声明为匿名函数(除非它占一行以上,否则不需要用大括号括起来)。
在findIndex()
中,我使用了非常简单的includes()
方法来检查当前元素是否包含所需的子字符串。
https://stackoverflow.com/questions/4556099
复制相似问题