數(shù)據(jù)結(jié)構(gòu)set基本概念
集合是由一組無序且唯一(即不重復(fù))的項組成的,這個數(shù)據(jù)結(jié)構(gòu)使用了與有限集合相同的數(shù)學(xué)概念丸氛,應(yīng)用在計算機(jī)的數(shù)據(jù)結(jié)構(gòu)中盟蚣。特點是key和value相同凰狞,沒有重復(fù)的value老虫。
了解完概念之后我們來看看怎么創(chuàng)建一個set數(shù)據(jù):
const s = new set([1,2,3]); //接收一個數(shù)組作為參數(shù)辞做,打印出Set(3) {1, 2, 3}
set結(jié)構(gòu)的自帶屬性:
console.log(s.size); //3
set數(shù)據(jù)實例的方法:
1.set.add(value); //添加一個數(shù)據(jù)厌小,返回set本身简肴。
s.add('a').add('b') //console.log(s) //{1,2,3,a,b}
2.set.delete 刪除指定數(shù)據(jù),返回布爾值榨咐,表示是否刪除成功介却。
s.delete('a') //返回 true 再執(zhí)行一次返回false
3.set.has(value) 判斷value是否是set的成員,返回布爾值块茁。
console.log('a') //false console.log('1') //true
4.set.clear() 清除所有數(shù)據(jù)齿坷,無返回值。
5.keys() 返回鍵名遍歷。
s.keys() //返回所有的鍵名 {1,2,3,b}
6.values() 返回值得遍歷
s.values() // 返回所有的值 {1,2,3,b}
7.entries() 返回所有的鍵值對遍歷
s.entries() // {[1,1],[2,2,],[3,3,],[b,b]}
8.forEach() 使用回調(diào)遍歷每個成員
s.forEach(function(value,key,set){
console.log(value +','key)
})
//1,1
//2,2
//3,3
//set可以省略
了解了set數(shù)據(jù)結(jié)構(gòu)屬性和方法那么它能做什么呢胃夏?
接下來我們來說一個set數(shù)據(jù)結(jié)構(gòu)的應(yīng)用轴或。
很多前端出去面試的時候都會遇到一個問題 ---數(shù)組去重。
之前的做法:
1重復(fù)遍歷數(shù)組拿一項去和其它項做對比等到一個新數(shù)組.
Array.prototype.unique1 = function(){
var res = [this[0]];
for(var i = 1; i < this.length; i++){
var repeat = false;
for(var j = 0; j < res.length; j++){
if(this[i] == res[j]){
repeat = true;
break;
}
}
if(!repeat){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
arr.unique1() //[1, "a", "b", "d", "e", 0]
2.利用對象key值得唯一性來實現(xiàn):
Array.prototype.unique2 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
arr.unique2() //[112, 34, "你好", "str", "str1"]
3.現(xiàn)在es6我們可以利用set數(shù)據(jù)的特點key和value相同仰禀,沒有重復(fù)的value來實現(xiàn)照雁。
const arr = [{}, 1, 'a', 1, 'a', 'b', []];
res = [...new Set(arr)]
console.log(res); //[Object, 1, "a", "b", Array(0)]
以上都是個人理解如有不對之處還望指正交流!