美文网首页
★ Set、Map、WeakSet、WeakMap

★ Set、Map、WeakSet、WeakMap

作者: 行走的蛋白质 | 来源:发表于2019-07-15 23:40 被阅读0次

    Set

    • 数据结构是集合,类似数组只有键值没有键名
    • 成员是唯一且无序的所以不能用索引来获取值
    • 可以遍历,方法有 add delete has size clear 等
    WeakSet
    • 成员只能是对象
    • 不能用来遍历,方法和 Set 基本相同
    • 成员都是弱引用,可以被垃圾回收机制回收,可以用来保存DOM节点,不容易造成内存泄漏
    // 创建
    const colors = new Set();
    const fruits = new Set(['apple', 'banana', 'orange']);
    
    // 添加元素
    colors.add('red');
    colors.add('blue');
    colors.add('green');
    
    // 获取长度
    colors.size
    
    // 删除元素
    colors.delete('red');
    
    // 检验元素是否存在
    colors.has('blue'); // true
    
    // 清除所有元素
    colors.clear();
    
    // 遍历
    colors.values(); // 返回 Iterator 结构,可以用 next 来进行遍历
    for(let color of colors) {
        console.log(color);
    } 
    colors.forEach((item, key, ownSet) => {
        // item 值
        // key 键
        // ownSet 自己 
        console.log(item, key, ownSet);
    })
    
    // 数组去重
    const numbers = [1, 2, 3, 4, 3, 2, 1];
    const numbersSet = new Set(numbers);
    const uniqueNumbers = [...numbersSet]; // [1, 2, 3, 4]
    

    Map

    • 数据结构是字典,类似对象存储的是键值对的集合,key 可以 set 任意类型的数据。
    • 可以遍历,方法有 set get delete size has clear 等
    WeakMap
    • 键名只能是对象 ( null 除外 ),键值可以是任意的,键名所指向的对象可以被垃圾回收,此时键名是无效的
    • 不能遍历,方法同 Map 基本一致
    // 创建
    const people = new Map();
    const fruits = new Map([['apple', 2], ['banana', 3]])
    
    // 添加元素
    people.set('protein', 22);
    people.set('mary', 21);
    people.set('jelly', 20);
    people.set({}, 3)
    
    // 获取长度
    people.size
    
    // 获取元素
    people.get('protein'); // 22
    
    // 删除元素
    people.delete('mary');
    
    // 检验元素是否存在
    people.has('protein'); // true
    
    // 清除所有元素
    people.clear();
    
    // 遍历
    for(let person of people) {
        console.log(person); // [key, value]
    } 
    for(let [key, value] of people) { // 解构
        console.log(key, value); 
    } 
    people.forEach((item, key, ownSet) => {
        // item 值
        // key 键
        // ownSet 自己 
        console.log(item, key, ownSet);
    })
    

    Map 的应用场景:当你想要存储关于这个对象的信息,而不是把这个信息存储到这个对象中的时候,就可以使用 Map 来操作。

    <button>Fire</button>
    <button>Dancer</button>
    <button>Ice Cream</button>
    <button>hamburger</button>
    <button>Fish</button>
    
    <script>
    
    const clickCounts = new Map();
    
    const buttons = document.querySelectorAll('button');
    
    buttons.forEach(button => {
        clickCounts.set(button, 0);
    
        button.addEventListener('click', function(){
            const val = clickCounts.get(this);
    
            clickCounts.set(this, val + 1);
    
            console.log(clickCounts);   
        })
    })
    
    </script>
    

    相关文章

      网友评论

          本文标题:★ Set、Map、WeakSet、WeakMap

          本文链接:https://www.haomeiwen.com/subject/iitakctx.html