The set methods are: 1. add(), used to add elements to the set; 2. delete(), used to delete an element in the set; 3. has(), used to determine whether the specified element Exists in the collection; 4. clear(), used to clear the collection elements; 5. forEach(), used to traverse the elements in the collection.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
The Set collection is very similar to the Arry array, but the Set collection stores keys, which means that there cannot be two in the Set collection. Keys whose values and data types are equal
Set collections cannot use subscripts to obtain values
Set collections do not have a length attribute but size
Set collections can be converted into real arrays through Array.from
Parameters | Type | Description | |
---|---|---|---|
None | Attribute | Get the length of the collection | |
Object | Method | Add elements to the collection | |
key | Method | Delete an element in the collection and return true if the deletion is successful | |
key | Method | Determines whether the specified element exists in the collection, and returns true if it exists | |
empty | Method | Clear the collection elements | |
function | Method | Traverse the elements in the collection Element |
##size attributevar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
console.log(set.size) //打印8
console.log(set.length) //打印undefined
add methodvar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
console.log(set.add("qq")); //打印{"sd",68,86,38,64,"qweq",58,"68",86,"qq"} 说明添加成功了
console.log(set.add("qq")); //依旧打印{"sd",68,86,38,64,"qweq",58,"68",86,"qq"} 说明重复的并没有被添加
delete methodvar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
console.log(set.delete("68")); //打印true说明删除成功
console.log(set.delete("68")); //打印false说明删除失败因为集合中已经不存在"68"
console.log(set); //打印 {"sd",68,86,38,64,"qweq",58,86} "68已被删除"
has methodvar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
console.log(set.has(68)); //返回true说明68在集合中存在
set.delete(68); //这里把68删除
console.log(set.has(68)); //返回false说明68在集合中不存在
clear methodvar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
set.clear(); //清空集合
console.log(set.size); //打印结果为0 说明集合已经被清空了
console.log(set); //打印结果{} 说明集合已经被清空了
forEach methodvar set = new Set(["sd",68,86,38,64,"qweq",58,"68",86]);
set.forEach(function(item,index,set){
console.log(item,index,set);
//打印结果 item是每一个集合元素的值 index与item的结果一致 set是集合本身
//在这里index和set可以不需要
})
The above is the detailed content of What are the methods of set collection in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!