JavaScript Set集合的并集,交集,差集

来源:互联网 发布:java依赖注入 编辑:程序博客网 时间:2024/06/04 19:12
/** * 返回两个集合的并集 */function union(thisSet, otherSet) { //初始化一个新集合,用于表示并集。 var unionSet = new Set(); //将当前集合转换为数组,并依次添加进unionSet var values = Array.from(thisSet); for (var i = 0; i < values.length; i++) {  unionSet.add(values[i]); }  //将其它集合转换为数组,依次添加进unionSet。 //循环中的add方法保证了不会有重复元素的出现 values = Array.from(otherSet); for (var i = 0; i < values.length; i++) {  unionSet.add(values[i]); }  return unionSet;};/** * 返回两个集合的交集 */function intersection(thisSet, otherSet) { //初始化一个新集合,用于表示交集。 var interSectionSet = new Set(); //将当前集合转换为数组 var values = Array.from(thisSet); //遍历数组,如果另外一个集合也有该元素,则interSectionSet加入该元素。 for (var i = 0; i < values.length; i++) {   if (otherSet.has(values[i])) {   interSectionSet.add(values[i])  } }  return interSectionSet;};/** * 返回两个集合的差集 */function difference(thisSet, otherSet) { //初始化一个新集合,用于表示差集。 var differenceSet = new Set(); //将当前集合转换为数组 var values = Array.from(thisSet); //遍历数组,如果另外一个集合没有该元素,则differenceSet加入该元素。 for (var i = 0; i < values.length; i++) {   if (!otherSet.has(values[i])) {   differenceSet.add(values[i])  } }  return differenceSet;};

3 0