介绍
本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:ES6 学习笔记
SET
Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SET</title>
</head>
<body>
<script>
colors = new Set();
colors.add('red');
colors.add('green');
// 添加数字 5
colors.add(5);
// 添加字符串 5
colors.add('5')
// 判断是否包含‘5’
colors.has('5') // 如果包含返回true,否则else
// 移除所有元素
colors.clear()
// 删除
colors.delete(5)
// 获取set长度
colors.size()
const iterator = colors.values() // 返回SetIterator,可以调用next()
iterator.next() // 返回set的第一个值
// 初始化时传入数据
const fruit = new Set(['apple','banana','bear'])
// for... of..
for(color of colors){
console.log(color);
}
// foreach
colors.foreach((item,key,ownSet)=>{
console.log()
})
// 对数组去重
const numbers=[1,2,3,4,5,5,5,5];
const numbersSet=new Set(numbers);
const uniquenumber=[...numbersSet];// 扩展运算符
</script>
</body>
</html>
WeakSet:
1、元素只能是对象
2、不支持for of 循环
3、不支持foreach方法
4、没有clear()方法
5、weakSet有自动清理的机制,可以防止内存泄漏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SET</title>
</head>
<body>
<script>
let jelly = {name: 'jelly',age: 20};
let mary = {name: 'mary',age: 25};
const people = new WeakSet([jelly,mary]);
</script>
</body>
</html>