如何制作一个函数,该函数采用两个字符串 returns 等值的集合? (Javascript)

How to make a function that takes two sets with strings that returns the equivalent values? (Javascript)

//编辑:我正在使用 Codehs 来解决这个问题,它没有使用过滤器或有'

函数开始(){

var gifts = ["book","car"]; 

var presents = ["game","book"];

 var tim = new Set();

 var sally = new Set();

tim.add(gifts);

sally.add(presents);

  var ans = compare(tim,sally);

  println(ans);

//should print in "book"
}

function compare(first,second){
//code here
}

我试过遍历元素并使用 union set.union();。我不知道在哪里解决这个问题。谢谢!

您可以使用 filter() 和 `has() 过滤集合的内容。但首先你需要将数据正确地放入集合中。

这(很遗憾)行不通了:

tim.add(gifts);

因为它将整个数组添加为单个集合元素。您只能在创建集合时执行此操作:

var tim = new Set(gifts);

function start(){

    var gifts = ["book","car"]; 
    var presents = ["game","book"];   
    var tim = new Set(gifts);
    var sally = new Set(presents);
    
    var ans = compare(tim,sally);
    
    console.log(ans);
    
    }
    
function compare(first,second){
    return [...first].filter(item => second.has(item))
}
start()

请注意,如果您要查找同时属于两个集合的项目,则称为集合 intersection, not the set union

MDN 有一些各种集合操作的例子,包括一个交集:

var intersection = new Set([...set1].filter(x => set2.has(x)));

以下是您如何使用您的代码:

var compare = (a, b) => new Set([...a].filter(x => b.has(x)));

var gifts = new Set(["book", "car"]);
var presents = new Set(["game", "book"]);
var ans = compare(gifts, presents);

console.log(...ans);

您可以获得第一个集合的项目数组,并通过使用集合本身采用 Set 原型方法 has 来过滤它。

基本上是这样

[...first].filter(Set.prototype.has, second)
    ^^^^^                                    the Set
 ^^^                                         take Set as iterable
^        ^                                   into array
           ^^^^^^                            filter the array
                  ^^^^^^^^^^^^^^^^^          by borrowing a method of Set
                                     ^^^^^^  with a Set

正在将集合 first 转换为数组,并将 Array#filterthisArg 作为第二个参数。

function compare(first, second) {
    return [...first].filter(Set.prototype.has, second);
}

var gifts = ["book", "car"],
    presents = ["game", "book"],
    tim = new Set(gifts),
    sally = new Set(presents);

console.log(compare(tim, sally));