检测值是否在Javascript中的一组值中的最快方法 [英] fastest way to detect if a value is in a group of values in Javascript

查看:146
本文介绍了检测值是否在Javascript中的一组值中的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中有一组字符串,我需要编写一个函数来检测另一个特定的字符串是否属于这个组。

I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not.

最快的是什么实现这个的方法?是否可以将值组放入数组中,然后编写一个搜索数组的函数?

What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array?

我认为如果我将值保持排序并执行二进制搜索,它应该足够快。或者还有其他一些聪明的方法,可以更快地工作吗?

I think if I keep the values sorted and do a binary search, it should work fast enough. Or is there some other smart way of doing this, which can work faster?

推荐答案

使用哈希表,并执行以下操作:

Use a hash table, and do this:

// Initialise the set

mySet = {};

// Add to the set

mySet["some string value"] = true;

...

// Test if a value is in the set:

if (testValue in mySet) {
     alert(testValue + " is in the set");
} else {
     alert(testValue + " is not in the set");
}

这篇关于检测值是否在Javascript中的一组值中的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆