关于数据处理的快捷方式set

1.set

Set 本身是一个构造函数,可以去重

  1. const s1 = new Set();
  2.  console.log(s1); // Set(0)
// Array ['a', 'b'] 转 Set 
const s2 = new Set(['a', 'b']); 
console.log(s2); // Set(2)
console.log(s2.size); // 2
 
const s3 = new Set(['a', 'a', 'b', 'b']);
console.log(s3.size); // 2
console.log(s3); //Set(2)
 
// 用...操作符,将 Set 转 Array
const ary = [...s3];
console.log(ary); // Array(2)
// 用Array.from转数组
    1. let v = new Set([1,2,3,3,5])
    2.  let a = Array.from(v)

2.for  (item of mySet/...)

     keys():返回键名;

     values(): 返回键值;

     entries(): 返回键值对

     键名=键值

let mySet = new Set([1, 2, 3]);
 for(let item of mySet) {
    console.log(item);
 }
 // 1
 // 2
 // 3
 
 // 返回键名
 for(let item of mySet.keys()) {
   console.log(item); 
 }
 // 1
 // 2
 // 3
  
 // 返回键值
 for(let item of mySet.values()) {
   console.log(item); 
 }
 // 1
 // 2
 // 3
 
 // mySet 键名=键值
  
 // 返回键值对
 for(let item of mySet.entries()){
   console.log(item); 
 }
 // [1, 1] 
 // [2, 2]
 // [3, 3]

Set 中的特殊值:

Set 对象存储的值总是唯一的,所以需要判断两个值是否恒等。有几个特殊值需要特殊对待:

1.+0 与 -0 在存储判断唯一性的时候是恒等的,所以不重复;

2.undefined 与 undefined 是恒等的,所以不重复;

3.NaN 与 NaN 是不恒等的,但是在 Set 中只能存一个,不重复。

posted @ 2023-01-05 17:17  Harry宗  阅读(22)  评论(0)    收藏  举报