0
点赞
收藏
分享

微信扫一扫

JavaScript Set没你想的那么简单!

认真的老去 2021-09-25 阅读 49

Set

Set是unique(不同)元素的集合,其中每个元素可以是任何类型。Set也是元素的有序集合。这意味着元素的检索顺序将与插入顺序相同。

创建Set

const set = new Set();
console.log(set);

输出:

Set(0) {}

初始化Set并创建

const fruteSet = new Set(['?', '?', '?', '?']);
console.log(fruteSet);

输出:

Set(4) {"?", "?", "?", "?"}

添加元素

使用add(element)方法将元素添加到中Set。

// Create a set - saladSet
const saladSet = new Set();
// Add some vegetables to it
saladSet.add('?'); // tomato
saladSet.add('?'); // avocado
saladSet.add('?'); // carrot
saladSet.add('?'); // cucumber

console.log(saladSet);

好了,我们加了蔬菜。到目前为止的输出:

Set(4) {"?", "?", "?", "?"}

添加元素

saladSet.add('?');
console.log(saladSet);

输出仍然像以前一样,没有添加任何内容到saladSet,因为内部已经包含?
判断是否存在,?和?

使用该has(element)方法在Set中查找元素

有 ?, 所以返回true

console.log('是否有??', saladSet.has('?'));

没有?, 所以返回false

console.log('是否有??', saladSet.has('?'));

现在我们删除掉?,因为的不喜欢吃它,如果是茄子的话可能不会删除

saladSet.delete('?');

console.log('我不喜欢 ?, 从数组中删除:', saladSet);

现在的数组是这样的:

{"?", "?", "?"}

clear()

clear() 方法用于删除所有元素

saladSet.clear();
console.log('完成了:', saladSet);

输出:

完成了: Set(0) {}

values()

Set有一个values()函数,它返回一个SetIterator(迭代器)

//创建一个set
const houseNos = new Set([360, 567, 101]);

//调用`values()`方法获取一个`SetIterator`(迭代器)
console.log(houseNos.values());

输出:

SetIterator {360, 567, 101}

可以使用forEach或for-of循环获取所有项的值

keys()

因为Set没有键,所以需要调用keys()方法返回一个SetIterator来获取键

console.log(houseNos.keys());

输出:

SetIterator {360, 567, 101}

entries()

entries()方法返回SetIterator以检索值-值对

console.log(houseNos.entries());

输出:

SetIterator {360 => 360, 567 => 567, 101 => 101}

让我们列举一下

我们可以使用forEach 或者 for-of循环遍历Set

houseNos.forEach((value) => {
   console.log(value);
});

输出:

360
567
101

使用for-of

for(const value of houseNos) {
   console.log(value);
 }

集合和对象

Set可以具有任何类型的元素,甚至是对象

 const person = {
   'name': 'Alex',
   'age': 32
 };

const pSet = new Set();
pSet.add(person);
console.log(pSet);

输出:



现在,让我们更改对象的属性,然后将其再次添加到集合中。

const person = {
   'name': 'Alex',
   'age': 32
};

const pSet = new Set();
pSet.add(person);

person.name = 'Bob';
pSet.add(person);
console.log(pSet);

输出:


获取唯一值

Set数据结构最常见的用法是从数组获取唯一值。

// 创建我喜欢的水果
const mixedFruit = ['?', '?', '?', '?', '?', '?', '?',];

// 把水果存在Set集合中
const mixedFruitSet = new Set(mixedFruit);

console.log(mixedFruitSet);

输出:

Set(4) {"?", "?", "?", "?"}

Set 常用操作

比如,union,intersection,diference,superset,subset等用于Set和数组一起使用.

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);

Union (mysql里面也有这个知识)并集后集合

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);
// Union
const union = new Set([...first, ...second]);
console.log('Union:', union);

输出:

Union: Set(5) {1, 2, 3, 4, 5}

Intersection (交集)

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);
// Intersection
const intersection = new Set([...first].filter(elem => {
    return second.has(elem)
}));
console.log('Intersection:', intersection);

输出:

Intersection: Set(1) {3}

Difference (集合差)

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);
// Difference
const difference = new Set([...first].filter(elem => {
    return !second.has(elem)
}));

输出:

Difference: Set(2) {1, 2}

Superset(超集)

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);

// 是否超集?
const isSuperset = (set, subset) => {
  for (let elem of subset) {
     if (!set.has(elem)) {
         return false;
     }
  }
  return true;
}
console.log('isSuperset?', isSuperset(first, second));

输出:

isSuperset? false

结论

Set是一个很好的数据结构,可以作为JavaScript数组的附加组件使用。不过,与array相比,它没有太大的优势。当您需要维护一组不同的数据以执行集合操作(如并集、交集、差分等)时,请使用它。

举报

相关推荐

0 条评论