===
*****=
*****=
=set 集合===
*****=
*****=
*****=
== 一直以來,js只能使用陣列和物件來保持多個資料,缺乏像其他語言那樣擁有豐富的結合型別
。因此,es6 新增了兩種結合型別(set 和 map), 用於不同場景發揮作用。
1.set 用於存放不能重複的資料
如何建立乙個set
: 如 const sets =
newset()
;// 建立乙個沒有任何內容的set集合
const contentset =
newset
(iterable)
;// 建立乙個具有初始化內容的set集合,
內容來自迭代物件每一次迭代的結果,並且自動去重
2. 如何對set 集合進行後續操作
add(資料): 新增乙個資料到set集合末尾,如果資料已經存在,不存在任何操作
set 使用object.js 的方式來判斷兩個資料是否相同, 但是set任務 +
0 和 -
0 是相等的
has(資料): 判斷set中是否存在兩個相等的資料
delete
(資料): 刪除匹配的資料,返回是否刪除成功
clear()
: 清空整個set集合
3. 如何和陣列相互轉化
// 陣列使用set來去重
const s =
newset([
1,2,
3,4,
5,6,
7,8]
);const arr =
[...s]
;// 字串去重
const str =
"fsjfsjsjfifas"
;const s =
[...
newset
(str)].
join(""
);4. 如何遍歷
1. 由於set是迭代物件的屬性, 可以使用 for
of 來遍歷
2. 使用set內部提供的例項方法, foreach()
const s =
newset([
1,2,
3,4,
5,6,
7,8]
);s.
foreach
((item, index, obj)
=>
) 注意: set中的index 不是下標
求兩個陣列的交集,並集, 差級:
例如:const arr1 =[1
,2,3
,4,5
,6,7
,8,9
,0];
const arr2 =[1
,3,4
,5,6
,3,6
,7,9
];// 求並集
const s =
[...
newset
(arr1.
concat
(arr2))]
;const s1 =
[...
newset([
...arr1,
...arr2])]
; console.
log(s, s1,
'並集');
// 求交集
const s3 =
[...
newset
(arr1)].
filter
(item =>
)const s4 =
[...
newset
(arr1)].
filter
(item => arr2.
indexof
(item)
!==-1)
console.
log(s3, s4,
'交集');
// 求差值
const s5 =
[...
newset([
...arr1,
...arr2])]
.filter
(item =>
(arr1.
indexof
(item)
!==-
1&& arr2.
indexof
(item)
===-1)
||(arr2.
indexof
(item)
!==-
1&& arr1.
indexof
(item)
===-1)
);const s6 =
[...
newset([
...arr1,
...arr2])]
.filter
(item => s3.
indexof
(item)
!==-1)
; console.
log(s5, s6,
"差值"
)
es6學習總結
一 let和const 1.let宣告的變數只在它所在的 塊有效。2.let宣告的變數僅在塊級作用域內有效。3.不存在變數提公升。4.每個let宣告的變數都有各自的作用域。它所宣告的變數一定要在宣告後使用,否則報錯 5.暫時性死區 只要塊級作用域內存在let命令,它所宣告的變數就 繫結 bindin...
ES6學習總結
1.建立 let x newset 2.特性 對基本資料型別,會自動去重 3.方法 x.add 新增 x.delete 刪除 x.has 刪除是否存在,返回布林 x.clear 清空 x.keys 返回鍵名的遍歷器 x.values 返回鍵值的遍歷器 x.foreach function 遍歷 ar...
ES6學習筆記 Set和Map
set類似於陣列,但是沒有重複的值,成員是唯一的。set例項有兩個屬性 set.prototype.constructor指向set本身,set.prototype.size返回set例項的成員總數。set例項的方法分為兩大類 操作方法 用於運算元據 和遍歷方法 用於遍歷成員 array.from方...