概覽
Set
類似於數組,但是成員的值都是唯一的,沒有重複的;
Set
本身是一個構造函數,用來生成Set
數據結構;
不能區分 +0,-0;
認爲NaN不等於NaN;
不能區分對象,認爲兩個對象總是不相等的;
不能區分數組,認爲兩個數組總是不相等的;
Set
的基礎和數組去重
let arr = [2,3,4,5,1,'1',1,undefined,undefined,'undefined',null,NaN,NaN,+0,-0,{},{},[],[]];
function unique(arr){
return Array.from(new Set(arr))
}
let newArr = unique(arr);
let newArr1 = [...new Set(arr)]
console.log(newArr); // [1, "1", 2, 3, 4, 5, undefined, "undefined", null, NaN, 0, {}, {}, [], []]
console.log(newArr1); // [1, "1", 2, 3, 4, 5, undefined, "undefined", null, NaN, 0, {}, {}, [], []]
// 不能區分 +0,-0;認爲NaN不等於NaN;不能區分對象,認爲兩個對象總是不相等的。不能區分數組,認爲兩個數組總是不相等的。
console.log(new Set([+0,-0])); //Set(1) {0}
const set = new Set([1,2,3,4]);
console.log(set); // Set(4) {1, 2, 3, 4}
console.log(set.size); // 4
console.log(...set); // 1 2 3 4
Set
的屬性和方法
console.dir(Set);
// ƒ Set()
// arguments: (...)
// caller: (...)
// length: 0
// name: "Set"
// prototype: Set
// add: ƒ add()
// clear: ƒ clear()
// constructor: ƒ Set()
// delete: ƒ delete()
// entries: ƒ entries()
// forEach: ƒ forEach()
// has: ƒ has()
// keys: ƒ values()
// size: (...)
// values: ƒ values()
// Symbol(Symbol.iterator): ƒ values()
// Symbol(Symbol.toStringTag): "Set"
// get size: ƒ size()
// __proto__: Object
// Symbol(Symbol.species): (...)
// get Symbol(Symbol.species): ƒ [Symbol.species]()
// __proto__: ƒ ()
// [[Scopes]]: Scopes[0]
Set
的實例屬性
Set.prototype.constructor
:構造函數,默認就是Set函數.Set.prototype.size
:返回Set實例的成員總數.
Set
的操作方法
add(value)
:添加某個值,返回Set結構本身delete(value)
:刪除某個值,返回一個布爾值,表示刪除是否成功。has(value)
:返回一個布爾值,表示參數是否爲Set的成員clear()
:清空所有成員,沒有返回值
const S = new Set();
S.add(1).add(2).add(2);
console.log(S); // Set(2) {1, 2}
console.log(S.size); // 2
console.log(S.has(1)); // true
console.log(S.has(2)); // true
console.log(S.has(3)); // false
S.delete(2);
console.log(S.has(2)); //false
console.log(S.size); // 1
S.clear();
console.log(S.size); // 0
// 判斷是否包括一個鍵
const properties = new Set();
properties.add('width');
properties.add('height');
if(properties.has('width')){
// do something
}
// Array.from()可以將Set結構轉換成數組
const items = new Set([1,2,3,4,5]);
const array = Array.from(items);
console.log(items,array); // Set(5) {1, 2, 3, 4, 5} [1, 2, 3, 4, 5]
Set
的遍歷操作(用於遍歷成員)
keys()
: 返回鍵名values()
: 返回鍵值entries()
: 返回鍵值對forEach()
: 使用回調函數遍歷每個成員
let set1 = new Set(['red','green','blue']).add('yellow');
for(let item of set1.keys()){
console.log(item);
// red
// green
// blue
// yellow
}
for (let i of set1.values()) {
console.log(i);
// red
// green
// blue
// yellow
}
for (let i of set1) {
console.log(i);
// red
// green
// blue
// yellow
}
for (let i of set1.entries()) {
console.log(i);
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
// ["yellow", "yellow"]
}
let set2 = new Set([1,2,3]);
set2.forEach(value=>console.log(value*2));
// 2
// 4
// 6
...
運算符遍歷
const setN = new Set([1,2,3]);
let newSetN = new Set([...setN].map(x=>x*2));
console.log(newSetN); // Set(3) {2, 4, 6}
const setM = new Set([1,2,3,4,5]);
let newSetM = new Set([...setM].filter(x=>(x%2===0)));
console.log(newSetM); // Set(2) {2, 4}
const a = new Set([1,2,3]);
const b = new Set([4,2,3]);
const c = new Set([...a,...b]);
console.log(c); // Set(4) {1, 2, 3, 4}
const d = new Set([...a].filter(x=>b.has(x)));
console.log(d); // Set(2) {2, 3}
const e = new Set([...a].filter(x=>!b.has(x)));
console.log(e); // Set(1) {1}
WeakSet
語法:
new WeakSet([iterable]);
WeakSet.prototype.add(value);
WeakSet.prototype.has(value);
WeakSet.prototype.delete(value);
和Set
的區別:
- 第一,
WeakSet
的成員只能是對象,而不能是其他類型的值; - 第二,
WeakSet
中對象都是弱引用,即垃圾回收機制不考慮WeakSet
對該對象的引用,也就是說,如果其他對象都不再引用該對象,那麼垃圾回收機制會回收該對象所佔用的內存,不考慮該對象是否還存在於WeakSet
之中; - 第三,
WeakSet
不能對其元素進行迭代,並沒有那麼多使用情形; - 第四,沒有size屬性。
使用:
let set = new WeakSet();
const class_1 = {}, class_2 = {};
set.add(class_1);
set.add(class_2);
console.log(set) // WeakSet {Object {}, Object {}}
console.log(set.has(class_1)) // true
console.log(set.has(class_2)) // true
Map
JavaScript的對象本質上是鍵值對的集合(Hash結構),但是隻能用字符串作爲鍵;
Map
類似於對象,也是鍵值對集合,各種類型的值(包括對象)都能當做鍵;
+0,-0Map
視爲一個鍵;
NaN
,NaN
Map
視爲一個鍵;
const m = new Map();
const o = {p:'hello world'};
m.set(o, 'content');
console.log(m.size); // 1
console.dir(m); // Map(1)
console.log(m.get(o)); // 'content'
console.log(m.has(o)); // true
m.delete(o)
console.log(m.has(o)); // false
創建Map
const mapOne = new Map([
[1,'one'],
[2,'two'],
[3,'three']
]);
const mapTwo = new Map()
.set(1,'one')
.set(2,'two')
.set(3,'three');
console.log(mapOne,mapTwo); // Map(3) {1 => "one", 2 => "two", 3 => "three"} Map(3) {1 => "one", 2 => "two", 3 => "three"}
Map
的基礎用法
const map = new Map([
['name','張三'],
['title','author']
]);
console.log(map); // Map(2) {"name" => "張三", "title" => "author"}
console.log(map.size); // 2
console.log(map.has('name')); // true
console.log(map.get('name')); // '張三'
console.log(map.has('title')); // true
console.log(map.get('title')); // 'author'
const items = [['name','張三'],['title','author']];
const mapItems = new Map();
items.forEach(
([key,value]) => mapItems.set(key,value)
)
console.log(mapItems); // Map(2) {"name" => "張三", "title" => "author"}
各類Map的鍵
- NaN
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
const mapNaN = new Map().set(NaN,'NaN123');
console.log(mapNaN.get(NaN)); // 'NaN123'
- +0,-0
console.log(+0 === -0); // true
console.log(Object.is(+0, -0)); // true
const map00 = new Map().set(+0,'000');
console.log(map00.get(-0)); // '000'
- {}
console.log(new Map().set({},1).set({},2).size); // 2
- []
console.log(new Map().set([],1).set([],2).size); // 2
- true,false,null,undefined,'true'
const mapAll = new Map();
mapAll.set(true,true).set('true','true').set(undefined,1).set(null,2);
console.log(mapAll.get(true),mapAll.get('true'),mapAll.get(undefined),mapAll.get(null)); // true 'true' 1 2
注意:不存在的屬性鍵返回undefined
console.log(new Map().get('abcsdff')); // undefined
注意:不僅僅是數組,任何具有Iterator接口且每個成員都是一個雙數組的數據結構都可以當作Map構造函數的參數。
const set = new Set([['foo',1],['bar',2]]);
const m1 = new Map(set);
console.log(m1.get('foo')); // 1
注意:對同一個鍵賦值,後面的值會覆蓋前面的值
const mapNew = new Map();
mapNew.set(1, 'aaa').set(1, 'bbb');
console.log(mapNew.get(1)); // 'bbb'
console.log(mapNew.get('11dasda')); // undefined
注意:只有對同一對象的引用,Map結構纔將其視爲同一個鍵。
const mapA = new Map()
mapA.set(['a'], 555);
console.log(mapA.get(['a'])); // undefined
let aa = ['a'];
mapA.set(aa, 555);
console.log(mapA.get(aa)); // 555
注意:同樣的值的兩個實例在Map結構中被視爲兩個鍵,簡單類型值除外(數字,字符串,布爾值)
const mapSame = new Map();
const k1 = ['a'];
const k2 = ['a'];
mapSame.set(k1,111).set(k2,222);
console.log(mapSame.get(k1),mapSame.get(k2)); // 111 222
const k3 = {a:1};
const k4 = {a:1};
mapSame.set(k3,123).set(k4,234);
console.log(mapSame.get(k3),mapSame.get(k4)); // 123 234
const k5 = 1;
const k6 = 1;
mapSame.set(k5,456).set(k6,789);
console.log(mapSame.get(k5),mapSame.get(k6)); // 789 789
Map
的屬性、操作方法、遍歷方法
size
:返回Map結構的成員總數;
set(key,value)
:設置key所對應的鍵值,然後返回整個Map結構;如果key已經優質,則鍵值會被更新,否則就新生成改鍵;
get(key)
:讀取key所對應的鍵值,如果找不到key,則返回undefined;
has(key)
:返回一個布爾值,表示某個鍵是否在Map數據結構中;
delete(key)
:刪除某個鍵,返回true,如果失敗,則返回false;
clear()
: 清空所有成員,沒有返回值;
const map = new Map([
[false,'no'],
[true,'yes'],
[undefined,1],
[null,2],
[NaN,3],
[+0,4],
[{},5],
[[],6]
])
console.log(map);
// Map(8)
// [[Entries]]
// 0: {false => "no"}
// 1: {true => "yes"}
// 2: {undefined => 1}
// 3: {null => 2}
// 4: {NaN => 3}
// 5: {0 => 4}
// 6: {Object => 5}
// 7: {Array(0) => 6}
// size: 8
// __proto__: Map
console.log(map.size); // 8
map.set(NaN,33).set(-0, 44).set({},55).set([],66);
console.log(map);
// Map(10)
// [[Entries]]
// 0: {false => "no"}
// 1: {true => "yes"}
// 2: {undefined => 1}
// 3: {null => 2}
// 4: {NaN => 33}
// 5: {0 => 44}
// 6: {Object => 5}
// 7: {Array(0) => 6}
// 8: {Object => 55}
// 9: {Array(0) => 66}
// size: 10
// __proto__: Map
console.log(map.size); //10
console.log(map.get(false)); // 'no'
console.log(map.get(true)); // 'yes'
console.log(map.get(null)); // 2
console.log(map.get(undefined)); // 1
console.log(map.get(0)); // 44
console.log(map.get({})); // undefined
console.log(map.get([])); // undefined
console.log(map.get('abcdef')); // undefined
console.log(map.has(false)); //true
console.log(map.has(true)); //true
console.log(map.has(0)); //true
console.log(map.has(NaN)); //true
console.log(map.has({})); //false
console.log(map.has([])); //false
console.log(map.has('abcdef')); //false
map.set(undefined,11).set(null,22).set(true,'yesyes').set(false,'nono');
console.log(map.get(undefined)); // true
console.log(map.get(null)); // 22
console.log(map.get(true)); // 'yesyes'
console.log(map.get(false)); // 'nono'
map.delete(undefined);
map.delete(null);
map.delete(true);
console.log(map.get(undefined)); // undefined
console.log(map.get(null)); // undefined
console.log(map.get(true)); // undefined
console.log(map.get(false)); // 'nono'
console.log(map.size); // 7
map.clear();
console.log(map.size); // 0
keys()
:返回鍵名;
values()
:返回鍵值;
entries()
:返回所有成員;
forEach()
:返回Map所有成員;
const map = new Map()
.set(1,'one')
.set(2,'two')
.set(3,'three')
for (const key of map.keys()) {
console.log(key);
// 1
// 2
// 3
}
for (const value of map.values()) {
console.log(value);
// 'one'
// 'two'
// 'three'
}
for (const [key,value] of map.entries()) {
console.log(key,value);
// 1 'one'
// 2 'two'
// 3 'three'
}
for (const [key,value] of map) {
console.log(key,value);
// 1 'one'
// 2 'two'
// 3 'three'
}
console.log([...map.keys()]); // [1,2,3]
console.log([...map.values()]); // ['one','two','three']
console.log([...map.entries()]); // [[1,'one'],[2,'two'],[3,'three']]
console.log([...map]); // [[1,'one'],[2,'two'],[3,'three']]
map.forEach((value,key,map)=>{
console.log(key,value);
// 1 'one'
// 2 'two'
// 3 'three'
})
// forEach方法還能接收第二個參數,用於綁定this
const reporter = {
report:(key,value)=>{
console.log(key,value);
// 1 'one'
// 2 'two'
// 3 'three'
}
}
map.forEach(function(value,key,map){
this.report(key,value)
},reporter)
const map1 = new Map(
[...map].filter(([k,v])=>k<3)
)
console.log(map1); // Map(2) {1 => "one", 2 => "two"}
const map2 = new Map(
[...map].map(([k,v])=>[k*2,"_"+v])
)
console.log(map2); // Map(3) {2 => "_one", 4 => "_two", 6 => "_three"}
與其他數據結構互相轉換
Map
和數組互轉
const myMap = new Map()
.set(true,7)
.set({foo:3},['abc']);
let arrMap = [...myMap]
console.log(arrMap); // [[true,7],[{foo:3},['abc']]]
console.log(new Map(arrMap)); // Map(2) {true => 7, {foo:3} => Array(1)}
Map
和對象互轉(=>obj需要Map
的所有鍵都是字符串)
function MaptoObj(strMap){
let obj = Object.create(null);
for (const [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
function ObjtoMap(obj){
let strMap = new Map();
for (const k of Object.keys(obj)) {
strMap.set(k,obj[k])
}
return strMap
}
const strMap = new Map([
['yes',true],
['no',false]
])
const endObj = MaptoObj(strMap)
console.log(endObj); // {yes: true, no: false}
console.log(ObjtoMap(endObj)); // Map(2) {"yes" => true, "no" => false}
Map
和JSON互轉(=>JSON:Map
鍵名都是字符串,可以轉爲對象JSON;還有非字符串,可以轉爲數組JSON。=>Map:對象JSON;數組JSON。)
// map轉對象JSON
function MaptoObjJSON(strMap){
return JSON.stringify(MaptoObj(strMap))
}
function MaptoObj(strMap){
let obj = Object.create(null);
for (const [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
const myMap = new Map()
.set('yes', true)
.set('no', false);
console.log(MaptoObjJSON(myMap)); // '{"yes":true,"no":false}'
// map轉數組JSON
function MaptoArrJSON(strMap){
return JSON.stringify([...strMap])
}
const myMap1 = new Map([
[true, 7],
[{foo:3},['abc']]
])
console.log(MaptoArrJSON(myMap1)); // '[[true,7],[{"foo":3},["abc"]]]'
// 對象JSON轉Map
function strJSONtoMap(strJson){
return ObjtoMap(JSON.parse(strJson))
}
function ObjtoMap(obj){
let strMap = new Map();
for (const k of Object.keys(obj)) {
strMap.set(k,obj[k])
}
return strMap
}
console.log(strJSONtoMap('{"yes":true,"no":false}')); // Map(2) {"yes" => true, "no" => false}
// 數組JSON轉Map
function ArrJSONtoMap(arrJson){
return new Map(JSON.parse(arrJson))
}
console.log(ArrJSONtoMap('[[true,7],[{"foo":3},["abc"]]]')); // Map(2) {true => 7, {…} => Array(1)}
WeakMap
和Map的區別:
沒有遍歷操作;
無法清空,不支持clear方法;
key是對象,值可以是任何值;
const wm = new WeakMap()
wm.set('abc', 123); // TypeError
wm.set({}, 123); // OK