1.Set集合方法
ES6提供了新的数据结构Set,类似于数组,元素值为唯一的,不能重复,Set实现了iterator接口,可以使用...
和for of
进行遍历
- new Set():构造方法,参数可以是数组,new Set([elem1, elem2])
- size属性:集合的元素个数
- add():增加一个新元素,返回当前集合
- delete():删除元素,返回 boolean 值
- has():检测集合中是否包含某个元素,返回 boolean 值
- clear():清空集合,返回 undefined
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>集合</title> </head> <body> <script> let s1 = new Set(); let s2 = new Set(["a", "b", "c", "a"]); console.log(s1); console.log(typeof s1); console.log(s2);
let size = s2.size; console.log(size);
s2.add('d'); console.log(s2);
for (let letter of s2) { console.log(letter); }
s2.delete('b'); console.log(s2);
let has_a = s2.has('a'); console.log(has_a);
s2.clear(); console.log(s2);
</script> </body> </html>
|
2.Set常见操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Set 实践</title> </head> <body> <script> let arr1 = [1, 2, 3, 4, 5, 4, 3, 2]; let set1 = new Set(arr1) let arr1_s = [...set1]; console.log(arr1_s);
let arr2 = [4, 5, 6, 5, 6]; let set2 = new Set(arr2); let arr2_s = [...set2]; let arr_unite = arr1_s.filter(item => { if(set2.has(item)) { return true; } else { return false; } }) console.log(arr_unite);
let arr_concat = [...arr1, ...arr2]; let merge_set = new Set(arr_concat); let arr_merge = [...merge_set]; console.log(arr_merge);
let arr_diff = arr1_s.filter((item) => { return !(set2.has(item)); }) console.log(arr_diff);
</script> </body>
</html>
|