Common methods of Set
1) The common attribute
size of Set: returns the number of elements in the Set.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr) // Set()括号中传入可迭代对象
// 4.size属性
console.log(arrSet.size); // 5
2) Common methods of Set
① add(value): Add an element and return the Set object itself.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
arrSet.add(100)
console.log(arrSet); //Set(6) {33,10,25,30,26,100}
② delete(value): Delete the element equal to this value from the set and return the boolean type.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
arrSet.delete(30) // delete方法括号中传入的必须是元素值,不能是索引
console.log(arrSet); //Set(4) {33,10,25,26}
③ has(value): Determine whether there is an element in the set, and return the boolean type.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
console.log(arrSet.has(33)); // true
④ clear(): Clear all the elements in the set, no return value.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
arrSet.clear()
console.log(arrSet); // Set(0) {}
⑤ forEach(callback, [, thisArg]): traverse the set through forEach.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
arrSet.forEach(item => {
console.log(item);
})
In addition, Set also supports for...of to traverse.
const arr = [33, 10, 25, 30, 33, 26]
const arrSet = new Set(arr)
for (const item of arrSet) {
console.log(item);
}