//Map和weakMap
//Map和它的方法使用
// 有Size属性
const users = new Map();
// String as key
users.set("John",{address:"John's Address"});
// Object as key
const obj = { name: "Michael"};
users.set(obj, {address: "Michael's Address"});
// Function as key
const func = () => "Andrew";
users.set(func, {address: "Andrew's Address"});
// NaN as key
users.set(NaN, {address: "NaN's Address"});
const contacts = new Map();
contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" });
contacts.has("Jessie"); // true
contacts.get("Hilary"); // undefined
contacts.delete("Raymond"); // false
console.log(contacts.size); // 1
//WeakMap **`WeakMap`** 对象是一组键/值对的集合,其中的键是弱引用的。<u>其键必须是对象,而值可以是任意的
//无Size属性,可以被垃圾回收,当没引用的时候,无序不保留状态
const test = new WeakMap();
const o1 = function(){}
test.set(o1, {name: "test"});
test.has(o1); //true
test.delete(o1);
test.has(o1); //false
JS中的Map()和weakMap()小例子
最新推荐文章于 2025-06-20 17:44:19 发布