NodeJS设计模式( 二 )

    xiaoxiao2023-10-17  172

    一、Map和Set集合

    const profiles = new Map() profiles.set( 'twitter','@adalovelance') profiles.set( 'facebook','adalovelance') profiles.seize profiles.has('twitter') profiles.get('twitter') profiles.has('youtube')//false profiles.delete('facebook') for (const entry of profiles){ console.log(entry) }

    Map真正有趣的地方是使用函数和对象作为key,而这时使用普通对象不可能完成的事情,因为对象的所有key都会自动转换为字符串。该功能带来了新的可能性。例如,我们可以利用此功能建立一个微测试框架:

    const tests = new Map() tests.set(()=>2+2,4) tests.set(()=>2*2,4) tests.set(()=>2/2,1) for(const entry of tests){ console.log((entry[0]()===entry[1])?'PASS':'FAIL') }

    set原型 可以用于轻松构建集合,一个所有值都唯一的列表

    const s = new Set([0,1,2,3]) s.add(3)//will not be added s.delete(0) s.has(0) for(const entry of s){ console.log(entry) }

    二、WeakMap和WeakSet集合

    同Map的差异 1、没办法迭代所有条目,只允许对象作为主键。 2、当它内部只剩下引用时,对象作为主键可以用来进行垃圾回收。当我们存储一个对象关联的元数据,而该对象在应用程序的正常生命周期可能被删除时,这个功能将非常有用

    const s = new Set([0,1,2,3]) let obj ={} const map = new WeakMap() map.set(obj,{key:"some_value"}) console.log(map.get(obj)) obj = undefined// 被垃圾回收了

    和WeakMap类似,WeakSe是Set的弱版本:它暴露出和Set相同的接口,但它只允许存储对象且不能重复 WeakSet允许内部对象在只剩下引用的时候被垃圾回收:

    let obj1 = {key: "val1"} let obj2 = {key: "val2"} const set = new WeakSet([obj1,obj2]) console.log(set.has(obj1)) obj1 = undefined// obj1 被移除 console.log(set.has(obj1))//false

    三、模板字面量

    ES6提供更强大的语法来定义字符串:模板字面量。这个语法使用反引号(`)作为分隔符 好处: 1、允许字符串中使用${experssion}插入变量或表达式 2、单个字符串可以轻松写在多行

    const name= "Leonardo" const interests = ["arts","architecture","science","music","mathematics"] const birth = { year:1452, place: 'Florence'} const text = `${name} was an Italian polymath interested in many topics such as ${interests.join(',')}. He was born in ${birth.year} in ${birth.place}.` const.log(text)
    最新回复(0)