Set数组字符串实用方法

添加元素

 let list = new Set();

list.add(1)

list.add(2).add(3).add(3)   // 2只被添加了一次

console.log(list);

 删除元素

let list=new Set([1,20,30,40])

list.delete(30)      //删除值为30的元素,这里的30并非下标

console.log(list);

判断某元素是否存在

let list=new Set([1,2,3,4])

console.log(list.has(2));

清除所有元素

let list=new Set([1,2,3,4])

list.clear()

console.log(list);

遍历 keys()

let list2=new Set(['a','b','c'])

for(let key of list2.keys()){

   console.log(key)//a,b,c

}  

遍历 values()

let list=new Set(['a','b','c'])

for(let value of list.values()){

console.log(value)//a,b,c

}

遍历 entries()

let list=new Set(['4','5','hello'])

for (let item of list.entries()) {

  console.log(item);

}  // ['4','4']  ['5','5']  ['hello','hello']

遍历 forEach()

let list=new Set(['4','5','hello'])

list.forEach((value, key) => console.log(key + ' : ' + value))   // 4:4    5:5  hello:hello

用于数组去重

let arr = [3, 5, 2, 2, 5, 5];

let setArr = new Set(arr)     // 返回set数据结构  Set(3) {3, 5, 2}

console.log(setArr);

//方法一   es6的...解构

let unique1 =  [...setArr ];      //去重转数组后  [3,5,2]

console.log(unique1);

//方法二  Array.from()解析类数组为数组

let unique2 = Array.from(setArr )   //去重转数组后  [3,5,2]

console.log(unique2);

用于字符串去重

let str = "352255";

let unique = [...new Set(str)].join("");     // 352

console.log(unique);

实现并集、交集、和差集

并集

let union = new Set([...a, ...b]);

// Set {1, 2, 3, 4}

console.log(union);

交集

let intersect = new Set([...a].filter(x => b.has(x)));

// set {2, 3}

console.log(intersect);

(a 相对于 b 的)差集

let difference = new Set([...a].filter(x => !b.has(x)));

// Set {1}

console.log(difference);

数组中取最小

console.log(Math.min.apply(Math,[1,2,3,54,7,45,84]));

数组中取最大

console.log(Math.max.apply(Math,[1,2,3,54,7,45,84]));

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容