【问题标题】:Merging sets with a mergeSets Generator functions使用 mergeSets 生成器函数合并集合
【发布时间】:2019-02-05 05:09:14
【问题描述】:

在这个话题中:Simplest way to merge ES6 Maps/Sets?

我找到了一种合并 Set 或 Map 的好方法

let set3 = new Set(function*() { yield* set1; yield* set2; }());

我想做一个可以像这样合并任意数量的集合的函数:

function  mergeSets() { 
    return new Set(function*() {
        for (const set of arguments) {
            yield* set
        }
    }())
}

我有办法吗?当我测试这个时,我得到一个空集作为结果

【问题讨论】:

    标签: javascript arrays set generator


    【解决方案1】:

    您正在使用您的arguments inside 内部function*,它会立即在没有参数的情况下被调用,因此arguments 是空的,因此对其进行迭代会导致返回的集合为空的。我会在外部函数中使用参数休息语法,将参数收集到适当的数组中,然后您可以遍历数组:

    (打开浏览器控制台,而不是 sn-p 控制台,查看生成的 Set:)

    const set1 = new Set(['1', '2', '3']);
    const set2 = new Set(['4', '5', '6']);
    const set3 = new Set(['7', '8', '9']);
    
    const mergeSets = (...sets) => new Set(function* () {
      for (const set of sets) yield* set;
    }());
    
    console.log(
      mergeSets(set1, set2, set3)
    );

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2017-05-02
      相关资源
      最近更新 更多