本文實例講述了ES6新特性五之Set與Map的數據結構。分享給大家供大家參考,具體如下:
1. Set
① 定義:它類似于數組,但是成員的值都是唯一的,沒有重復的值。Set本身是一個構造函數,用來生成Set數據結構。
var s = new Set();[2,3,5,4,5,2,2].map(x => s.add(x))console.log(s); //Set { 2, 3, 5, 4 }
② 屬性和方法
Set結構有以下屬性。
Set.prototype.constructor
:構造函數,默認就是Set函數。Set.prototype.size
:返回Set的成員總數。
Set數據結構有以下方法。
add(value)
:添加某個值,返回Set結構本身。delete(value)
:刪除某個值,返回一個布爾值,表示刪除是否成功。has(value)
:返回一個布爾值,表示該值是否為Set的成員。clear()
:清除所有成員,沒有返回值。
var s = new Set();s.add(1).add(2).add(2);// 注意2被加入了兩次console.log(s.size) // 2console.log(s.has(1)) // trueconsole.log(s.has(2)) // trueconsole.log(s.has(3)) // falseconsole.log(s.delete(2));console.log(s.has(2)) // false
③ Array.from方法可以將Set結構轉為數組
var items = new Set([1, 2, 3, 4, 5]);var arr = Array.from(items);//運用: 去除數組中重復元素的方法var array = [1,2,3,2,3,4];function fun(array) { return Array.from(new Set(array));}console.log(fun(array));//[ 1, 2, 3, 4 ]
④ Set結構有一個values方法,返回一個遍歷器。
var s = new Set([1, 2, 3, 4, 5]);console.log(s.values());//SetIterator { 1, 2, 3, 4, 5 }//Set結構的默認遍歷器就是它的values方法console.log(Set.prototype[Symbol.iterator] === Set.prototype.values)//true//所以遍歷可以直接使用 for...offor (let x of s) { console.log(x);}//由于擴展運算符(...)內部使用for...of循環,將Set轉化為數組。var arr = [...s];console.log(arr);//[ 1, 2, 3, 4, 5 ]
⑤ Set結構的foreach方法
var set = new Set([1, 2, 3]);set.forEach(function(value,key){ console.log(value);});
⑥ Set結構也有keys和entries方法,這時每個值的鍵名就是鍵值。
let set = new Set(['red', 'green', 'blue']);for ( let item of set.keys() ){ console.log(item);}// red// green// bluefor ( let [key, value] of set.entries() ){ console.log(key, value);}// red, red// green, green// blue, blue
⑦ 數組的map和filter方法的運用
map(x){}
: 遍歷數組,對每一元素進行處理,返回處理后的數組。filter(x){}
: 遍歷數組,對每一個元素進行校驗,返回含有通過校驗元素的數組。
var set = new Set([1, 2, 3]);set = new Set([...set].map(x => x * 2));console.log(set);//返回Set結構:{2, 4, 6}var set = new Set([1, 2, 3, 4, 5]);set = new Set([...set].filter(x => (x % 2) == 0));console.log(set);// 返回Set結構:{2, 4}
2. Map
① 原因:JavaScript的對象,本質上是鍵值對的集合,但是只能用字符串當作鍵。
② 定義:它類似于對象,也是鍵值對的集合,但是“鍵”的范圍不限于字符串,各種類型的值(包括對象)都可以當作鍵。
新聞熱點
疑難解答