简体   繁体   English

在字符串数组中查找字符串的最快方法

[英]Fastest way to find string in the array of strings

Suppose we have an array of strings, like this: 假设我们有一个字符串数组,如下所示:

var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];

but much longer. 但更长。 And a string, which is the user input. 还有一个字符串,这是用户输入的。

So, on every keyup (next character inserted in that string) I have to check if this string is present in that array. 因此,在每个keyup (在该字符串中插入下一个字符)上,我都必须检查该字符串是否存在于该数组中。

I know I can do it by looping through the array every time - but is there any way to make it faster? 我知道我可以通过每次遍历数组来做到这一点-但是有什么方法可以使其更快?

You can use the indexOf() function for that. 您可以为此使用indexOf()函数。

var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];
var str= 'rty';

var isPresent = (arr.indexOf(str) > -1);

To explain: indexOf() return the index of the string found in the array. 解释一下:indexOf()返回在数组中找到的字符串的索引。 If the string is not found, it returns -1. 如果找不到该字符串,则返回-1。 So...indexOf('qwe') returns 0, indexOf('rty') returns 1, etc. But indexOf('foo') returns -1. 因此... indexOf('qwe')返回0,indexOf('rty')返回1,依此类推。但是indexOf('foo')返回-1。

Use IndexOf() : 使用IndexOf()

var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];
arr.indexOf('a'); // returns 3
arr.indexOf('aaa'); // returns -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM