How to use the set method in es6?

The Set object in ES6 is a data structure similar to an array that allows you to store unique values of any type, whether they are primitive values or object references. The values in a Set object are unordered and cannot be duplicated.

There are a few steps to using the Set method:

  1. Create a Set object: You can create an empty Set object using new Set(), or create a Set object with initial values by using an array, such as new Set([1, 2, 3]).
  2. Add values: You can use the add() method of the Set object to add values to the Set object, for example set.add(value), where value is the value you want to add.
  3. Remove value: You can use the delete() method of a Set object to remove a value from the Set, for example set.delete(value), where value is the value you want to delete.
  4. To check if a value exists: You can use the has() method of a Set object to determine if a certain value is present in the Set. For example, set.has(value), where value is the value you want to check. It will return true if the value exists and false if it does not.
  5. Get the size of the Set: You can use the size property of the Set object to retrieve the number of values in the Set, for example set.size.
  6. Traverse a Set object: You can use the forEach() method of the Set object to iterate through the values in the Set, for example set.forEach(value => console.log(value)).

Here is an example using the Set method:

// 创建一个空的Set对象
const set = new Set();

// 添加值到Set对象中
set.add(1);
set.add(2);
set.add(3);

// 删除Set中的值
set.delete(2);

// 判断某个值是否存在于Set中
console.log(set.has(1)); // true
console.log(set.has(2)); // false

// 获取Set的大小
console.log(set.size); // 2

// 遍历Set对象
set.forEach(value => console.log(value)); // 1, 3

It is important to note that the values in a Set object are unique, so if you try to add a duplicate value to the Set, it will not take effect.

bannerAds