如何检查字符串是否存在于Immutable.Set<string[]>?已尝试方法均报错
检查Immutable集合中是否存在目标值的问题与解决方法
以下是我尝试的几种方法及对应的结果……我查阅了文档,感觉其中至少有几种方法应该可行,不清楚哪里出错了。
function getMatch( value: string, fooSet: Immutable.Set<string[]> ): boolean { // 将Immutable集合转为普通JS数组,以便使用includes方法 const setArray = fooSet.toArray(); return setArray.includes([value]); //TypeError: fooSet.toArray is not a function // 使用some方法检查值是否存在于集合中 let valueList = [value] return fooSet.some((key) => key === valueList); // fooSet.some is not a function return fooSet.has([value]); //has仅适用于数字,不能用于字符串数组 return fooSet.some((key) => key.is(value))//Property 'is' does not exist on type 'string[]' let found = fooSet.get([value]) return found ? true : false //fooSet.get is not a function }
更新解决方案
按照@Bergi的建议改为Set<List>,这是很大的改进。另一要点是需要将不可变对象与不可变对象进行比较,我的值是一个包含3个字符串的键,修复代码如下:
function getMatch( values: { key1: string; key2: string; key3: string }, fooSet: Immutable.Set<List<string>> ): boolean { const { key1, key2, key3 } = values const valueList = Immutable.List<string>([key1, key2, key3]) const containsValue = fooSet.some((list) => list.equals(valueList)); return containsValue; }
另外,我也可以只检查列表中的单个值:
const checkKey1 = (list: Immutable.List<string>) => list.includes(key1); const hasKey1 = set.some(checkKey1);
内容的提问来源于stack exchange,提问作者tomtom
相关产品推荐
相关产品推荐

