★ Set、Map、WeakSet、WeakMap

2019-07-15  本文已影响0人  行走的蛋白质

Set

WeakSet
// 创建
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

WeakMap
// 创建
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>
上一篇下一篇

猜你喜欢

热点阅读