有效地查找集合中的项目 [英] Efficiently find an item in a Set

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

问题描述

如果我需要在Set中找到一个对象.该集合不包含用作索引的自然键,因此无法使用Map.有几种不同类型的谓词可用于搜索集合.看来效率很低

if I need to find an object in a Set. The set does not contain a natural key to use as an index, so I can't use Map. There are several different types of predicates used to search the Set. It seems inefficient to do

const items = Array.from( mySet )
const found = items.find( item => someTest( item ) )

除非优化器中存在黑魔法,否则它似乎将被枚举两次.我知道它公开了一个迭代器接口,但是Array.prototype.find接口比使用带有break语句的for ... of循环更简洁.

Unless there's black magic in the optimiser, it seems like it will enumerate twice. I know it exposes an iterator interface, but the Array.prototype.find interface is much more concise than using a for...of loop with a break statement.

有更好的方法吗?

推荐答案

您具有> 具有 方法来查找值的存在.

You have has method on Set to find existence of value.

let set = new Set([1,2,4,5,6,7])

console.log(set.has(2))
console.log(set.has(10))

这篇关于有效地查找集合中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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