let set = new Set();
//1、添加元素
set.add('First');
set.add('Second');
set.add('Third').add('Fourth');
set.add('Second');
console.log(set); // {'First', 'Second', 'Third', 'Fourth'}
//2、获取长度
let size = set.size;
console.log(size); // 4
//3、元素是否存在
console.log(set.has('Second')); // true
console.log(set.has('HH')); // false
//4、遍历元素:方式1
for(let item of set){
console.log(item);
}
// First
// Second
// Third
// Fourth
//遍历键名key
// for (let item of set.keys()) {
// console.log(item);
// }
//遍历键值value
// for (let item of set.values()) {
// console.log(item);
// }
//遍历元素:方式2
set.forEach((value, key) =>{
console.log('value:',value, ', key:',key);
});
//value: First , key: First
//value: Second , key: Second
//value: Third , key: Third
//value: Fourth , key: Fourth
//5、将Set 转换为 数组
const array = Array.from(set);
console.log(array); // ['First', 'Second', 'Third', 'Fourth']
//6、获取元素在数组的索引位置
const index = array.indexOf('Third');
console.log(index) // 2
//7、删除元素
const isDel = set.delete('Third');
console.log(isDel); // true
console.log(set); // {'First', 'Second', 'Fourth'}
//8、清空元素
set.clear();
console.log(set); // []
03-30
1270
03-27
1万+