哈希表 Map
// 创建一个空的 Map
const hashMap = new Map();
// 添加键值对
hashMap.set("key1", "value1");
hashMap.set("key2", "value2");
// 访问值
console.log(hashMap.get("key1")); // 输出: value1
// 检查键是否存在
console.log(hashMap.has("key1")); // 输出: true
// 删除键值对
hashMap.delete("key1");
console.log(hashMap.has("key1")); // 输出: false
// 获取哈希表的大小
console.log(hashMap.size); // 输出: 1
// 遍历键值对
for (let [x, y] of hashMap) {
console.log(x)
console.log(y)
}
集合 Set
// 创建一个新的Set
const mySet = new Set();
// 添加元素到Set
mySet.add(1);
mySet.add(5);
mySet.add("hello");
mySet.add({ name: "Alice" });
// Set中的值是唯一的,重复添加相同的值不会生效
mySet.add(5); // 不会添加,因为5已经存在
// 检查Set中是否包含某个值
console.log(mySet.has(1)); // 输出: true
console.log(mySet.has(10)); // 输出: false
// 获取Set的大小
console.log(mySet.size); // 输出: 4
// 遍历Set中的元素
mySet.forEach((value) => {
console.log(value);
// 输出:
// 1
// 5
// hello
// { name: 'Alice' }
});
// 使用for...of循环遍历Set
for (let item of mySet) {
console.log(item);
// 输出:
// 1
// 5
// hello
// { name: 'Alice' }
}
// 删除Set中的某个元素
mySet.delete(5);
console.log(mySet.has(5)); // 输出: false
// 清空Set中的所有元素
mySet.clear();
console.log(mySet.size); // 输出: 0
// 使用数组初始化Set
const myArray = [1, 2, 3, 4, 4, 5];
const mySetFromArray = new Set(myArray);
console.log([...mySetFromArray]); // 输出: [1, 2, 3, 4, 5]
// Set与数组的转换
const myArrayFromSet = Array.from(mySetFromArray);
console.log(myArrayFromSet); // 输出: [1, 2, 3, 4, 5]
// Set与字符串的转换
const myString = "hello";
const mySetFromString = new Set(myString);
console.log([...mySetFromString]); // 输出: ['h', 'e', 'l', 'o']
// 使用Set进行数组去重
const duplicateArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(duplicateArray)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
// Set的并集、交集、差集操作
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
// 并集
const union = new Set([...setA, ...setB]);
console.log([...union]); // 输出: [1, 2, 3, 4]
// 交集
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log([...intersection]); // 输出: [2, 3]
// 差集
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log([...difference]); // 输出: [1]
Comments NOTHING