The set collection of es6 can use the add() method to add elements. Set is a data structure with a structure similar to an array and has no duplicate values; its built-in add() method can add elements to the set, the syntax is "set.add(value);", and the Set structure will be returned after the addition is completed. itself.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Set collection: It is a data structure with a structure similar to an array and has no duplicate values. Mainly used for array deduplication and string deduplication.
(1) add(): add value and return the Set structure itself
let set = new Set() set.add(1); console.log(set); set.add(1).add(2).add(1) console.log(set) //注:拓展运算符 (...)可以将Set值扩展出来 console.log(...set) console.log([...set])
(2) delete(): delete the value, return a boolean to indicate whether the deletion is successful (3) has(): determine whether the value exists, and return a Boolean
let set = new Set() set.add(1).add(2); let a = set.delete(1); console.log(set) //注:拓展运算符 (...)可以将Set值扩展出来 console.log(...set) console.log(a) set.delete(3) console.log(...set)
(3) has(): Determine whether the value exists and return a Boolean
let set = new Set() set.add(1).add(2); let a = set.has(1);//true let b = set.has(3);//false console.log(a,b)
(4) clear(): Clear all values. No return value
let set = new Set(); set.add(1).add(2); set.clear(); console.log(set,[...set]);//Set(0){} []
(1) Since Set only has key values and no key names, it can also be said that the key and The value is the same (the key and value are the same and can be omitted), so the return values of keys and values are the same
let set = new Set(); set.add(1).add(2).add(3) for(let i of set.keys()){ //keys遍历 console.log(i) } for(let i of set.values()){ //values遍历 console.log(i) } set.add('hello').add('world'); for( let i of set.entries() ){ //打印键值对 console.log(i) }
(2) forEach():
let set = new Set(); set.add('hello').add('world'); set.forEach((key,val)=>{ console.log(key + '||' + val) })
(3) Set can accept an array as a parameter:
let arr = ['小红','小明','小强','小明']; let set = new Set(arr); console.log(...set)
(4) Set implements union and intersection:
let arr = [4,5,6]; let list = [5,6,7]; let setA = new Set(arr); let setB = new Set(list); //并集 :集合A与集合 B的并集A U B let bj = new Set([...setA,...setB]) console.log(bj)// 返回Set结构 Set(4) {4,5,6,7} //交集:集合A 与 集合B 的交集 A ∩ B let jj = new Set([...setA].filter(val => setB.has(val)))//通过 filter拿到符合条件的值 console.log(jj)//Set(2) { 5, 6 }
【Related recommendations: javascript video tutorial, programming video】
The above is the detailed content of How to add elements to the set collection in es6. For more information, please follow other related articles on the PHP Chinese website!