十五.新增資料結構Map,Set,WeakMap和WeakSet
-
- 1.Set資料結構
- 2.Map資料結構
- 3.弱連接配接資料結構
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中沒有相應表達