简体   繁体   English

什么是检查javascript中字符串集合中是否存在字符串的最快方法?

[英]Whats the fastest way to check if a string exists in a string collection in javascript?

In JavaScript, I need some data structure that can hold strings, and has a fast way to search if a string exists in it, and to insert a string in it. 在JavaScript中,我需要一些可以保存字符串的数据结构,并且可以快速搜索字符串是否存在于其中,并在其中插入字符串。

I was planning to use an array, but I am currently using a dictionary where the key is the string and the value is just 'true' even through I don't use it. 我打算使用一个数组,但我目前正在使用一个字典,其中键是字符串,即使我不使用它,值也只是'true'。

I went with dictionary because I would think it would be something like an AVL tree, where the insert, delete and add are all O(log(n)) time. 我选择了字典,因为我觉得它会像AVL树一样,插入,删除和添加都是O(log(n))时间。 And the array would have an insert, delete, and search of O(n) time. 并且数组将插入,删除和搜索O(n)时间。

Is this right, or is there a better way? 这是对的,还是有更好的方法?

Thanks 谢谢

Use an object. 使用对象。

Add string: 添加字符串:

obj[string] = true;

Check if string exists: 检查字符串是否存在:

obj.hasOwnProperty(string);
// or simply
obj[string]

If you use an array. 如果使用数组。

You can use indexOf() to find the position. 您可以使用indexOf()来查找位置。 And splice() to insert a string into array object. 并且splice()将一个字符串插入到数组对象中。 Also if position does not matter, use push() . 此外,如果位置无关紧要,请使用push()

This should be fast enough, it is in JS library. 这应该足够快,它在JS库中。

EDIT: 编辑:

Both indexOf() and splice() are linear. indexOf()splice()都是线性的。

var stringStore = {}; var stringStore = {};

stringStore['sample-string-1'] = 'sample-string-1'; stringStore ['sample-string-1'] ='sample-string-1';

stringStore['sample-string-2'] = 'sample-string-2'; stringStore ['sample-string-2'] ='sample-string-2';

if (stringStore['sample-string-2'] ) console.log("string 2 exists"); if(stringStore ['sample-string-2'])console.log(“string 2 exists”); else console.log("string 2 doesn't exists"); else console.log(“string 2不存在”);

if (stringStore['sample-string-3'] ) console.log("string 3 exists"); if(stringStore ['sample-string-3'])console.log(“string 3 exists”); else console.log("string3 doesn't exists"); else console.log(“string3不存在”);

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

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