高效的Javascript数组查找 [英] Efficient Javascript Array Lookup

查看:61
本文介绍了高效的Javascript数组查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串白名单,我想检查用户输入我的javascript程序的所有内容,那么最有效的方法是什么?我可以只有一个数组并循环遍历它,直到找到匹配但是那是O(N)。有没有做得更好,并且不涉及任何类型的键值查找,只是检查该值是否存在?

If I have a whitelist of strings that I want to check everything the user inputs into my javascript program, what's the most efficient way to do that? I could just have an array and loop through it until a match has been found but that's O(N). Is there an yway to do it that's better and doesn't involve any sort of key value lookup, just checking to see if that value exists?

编辑:我想我正在寻找的是相当于C ++中的一个集合,我可以检查一下我给出的值是否已经存在于集合。

I guess what I'm looking for is the equivalent of a set in C++ where I can just check to see if a value I'm given already exists in the set.

推荐答案

只需将其设为简单的js对象而不是数组。

Just make it a simple js object instead of an array.

var whitelist = {
  "string1":true,
  "string2":true
}

然后你可以检查 if(whitelist [str])来检查是否它是可用的。

and then you can just check if(whitelist[str]) to check if its available.

或者使用 if(str in whiteelist)

我希望第一个会有更好的性能(我没有验证过),但第二个更具可读性并且目的明确。所以你选择哪个更适合。

I expect that the first will have slightly better performance (I haven't verified that), but the second is more readable and makes the purpose clear. So its your choice of which is a better fit.

这篇关于高效的Javascript数组查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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