ECMAScript 6(ES6) 特性概览和与ES5的比较15-新增数据结构Map,Set,WeakMap和WeakSet

十五.新增数据结构Map,Set,WeakMap和WeakSet

1.Set数据结构

基于集合的更清晰的通用算法的数据结构
set是不重复的集合

ECMAScript 6

let s = new Set()
s.add("hello").add("goodbye").add("hello")
s.size === 2
s.has("hello") === true
for (let key of s.values())
    console.log(key)//插入顺序

//输出:hello goodbye

ECMAScript 5

var s = {};
s["hello"] = true; 
s["goodbye"] = true; 
s["hello"] = true;
Object.keys(s).length === 2;
s["hello"] === true;
for (var key in s)
    if(s.hasOwnProperty(key))
        console.log(s[key]); //任意顺序

2.Map数据结构

基于映射的更清晰的通用算法的数据结构

ECMAScript 6

let m = new Map()
let s = Symbol()
m.set("hello", 42)
m.set(s, 34)
m.get(s) === 34
m.size === 2
for (let [ key, val] of m.entries())
    //console.log(key + "=" + val) 会报错
    //Uncaught TypeError: Cannot convert a Symbol value to a string
    console.log(key,val)

ECMAScript 5

var m = {};
//ES5中没有相应表达
m["hello"] = 42;
//ES5中没有相应表达
//ES5中没有相应表达
Object.keys(m).length === 2;
for (key in m) {
    if (m.hasOwnProperty(key)) {
        var val = m[key];
        console.log(key + "=" + val);
    }
}

3.弱连接数据结构

内存泄漏对象密钥并排数据结构。WeakSet 和WeakMap中的引用不计入垃圾回收机制。

ECMAScript 6

let isMarked = new WeakSet()
let attachedData = new WeakMap()

export class Node {
    constructor (id) { this.id = id }
    mark () { isMarked.add(this) }
    unmark () { isMarked.delete(this) }
    marked () { return isMarked.has(this) }
    set data (data) { attachedData.set(this, data) }
    get data () { return attachedData.get(this) }
}

let foo = new Node("foo")

JSON.stringify(foo) === '{"id":"foo"}'
foo.mark()
foo.data = "bar"
foo.data === "bar"
JSON.stringify(foo) === '{"id":"foo"}'

isMarked.has(foo) === true
attachedData.has(foo) === true
foo = null /*仅删除对foo的引用*/
attachedData.has(foo) === false
isMarked.has(foo) === false

ECMAScript 5

//ES5中没有相应表达

猜你喜欢

转载自blog.csdn.net/u010622874/article/details/84068882