Set 是什么
Set 是一个无序,没有重复值的数据集合
- 理解Set
const s = new Set();
s.add(1);
s.add(2);
s.add(1);
console.log(s);
Set实例方法和属性
方法
const s = new Set();
s.add(1).add(2).add(2);
属性
/ console.log(s.size); Set 的长度
Set构造函数的参数
数组作为参数
const s = new Set([1, 2, 1]);
console.log(s);
字符串 ,arguments NodeList Set 等
const s = new Set("hp");
console.log(s);
function fn() {
console.log(new Set(arguments));
}
fn(1, 2, 1);
const p = document.querySelectorAll("p");
const s = new Set(p);
console.log(s);
const s = new Set("hp");
console.log(s);
function fn() {
console.log(new Set(arguments));
}
fn(1, 2, 1);
const p = document.querySelectorAll("p");
const s = new Set(p);
console.log(s);
Set的注意事项
判断重复的方式
const s = new Set([NaN, 2, NaN]);
console.log(s);
什么时候用Set
- 数组或字符串去重时
- 不需要通过下标访问,只需要遍历时
- 为了使用Set 提供的方法和属性时(add,has,delete,clear,forEacg,size)
Set的应用
数组去重
const arr = [1, 2, 1];
const s = new Set(arr);
字符串去重
const s = new Set("aabbccdd");
console.log([...s].join(""));
存放dome元素
const p = document.querySelectorAll("p");
const s = new Set(p);
s.forEach((k) => {
k.style.color = "red";
k.style.backgroundColor = "green";
});
Map是什么
const m = new Map();
m.set("name", "Ajsx");
console.log(m);
Map和对象的区域
- 对象一般用字符串当做建
- 基本数组类型:数子,字符串 布尔值 undefined null
- 引用数据类型:对象 ([],{},函数,Set,Map,等)
Map方法和属性
方法
- m.get()
- m.has
- m.delete
- m.clear
- m.forEach
属性
Map 构造函数的参数
数组
Map的注意事项
- 判断键名是否相同的方式
- 基本遵循严格相等(===)
- 例外就是NaN,Map中NaN也是等于 NaN
什么时候有Map
- 如果只需要key->value 的机构 或者需要字符串以外的值做键使用Map,更合适
- 只有模拟现实世界的实体时,才使用对象
Map的应用
方法1
const [p1, p2, p3] = document.querySelectorAll("p");
const m = new Map([
[p1, { color: "red", backgroundColor: "green" }],
[p2, { color: "green", backgroundColor: "blue" }],
[p3, { color: "blue", backgroundColor: "red" }],
]);
m.forEach((value, key) => {
for (let k in value) {
key.style[k] = value[k];
}
});
方法2
const [p1, p2, p3] = document.querySelectorAll("p");
const m1 = new Map([
["color", "red"],
["backgroundColor", "green"],
]);
const m2 = new Map([
["color", "green"],
["backgroundColor", "blue"],
]);
const m3 = new Map([
["color", "blue"],
["backgroundColor", "red"],
]);
const m = new Map([
[p1, m1],
[p2, m2],
[p3, m3],
]);
m.forEach((value, key) => {
value.forEach((value1, key1) => {
key.style[key1] = value1;
});
});
console.log(m);