定制软件开发js中Set基本使用

介绍

6 新增的 Set 定制软件开发是一种新集合类型,定制软件开发为这门语言带来集合数据结构。Set 在很多方面都像是加强的 Map,这是因为它们的大多数 API 和行为都是共有的。

基本API

1. 创建Set实例

使用 new 关键字和 Set 构造函数可以创建一个空集合:

const s = new Set();
  • 1

如果想在创建的同时初始化实例,则可以给 Set 构造函数传入一个,其中需要包含插入到新集合实例中的元素(Set 可以包含任何 JavaScript 数据类型作为值):

const s = new Set(["val1", 1, true, {}, undefined, function fun() {}]);
  • 1

注意:Set结构不会添加重复的值

const s = new Set([1, 1, 2, 3, 4, 4, 5, 6, 7, 4, 2, 1]);Array.from(s); //  [1, 2, 3, 4, 5, 6, 7]
  • 1
  • 2

经常用Set解决数组去重问题

const arr = [1, 2, 3, 3, 4, 5, 4, 4, 2, 1, 3];Array.from(new Set(arr)); // [1, 2, 3, 4, 5]
  • 1
  • 2

2. Set实例转数组

const s = new Set([1, 2, 3]);Array.from(s); // [1, 2, 3]
  • 1
  • 2

3. size属性

size: 获取Set实例的元素个数:

const s = new Set([1, 2, 3]);s.size; // 3
  • 1
  • 2

4. add()

add(): 添加元素:

const s = new Set();s.add(1).add(2).add(3);Array.from(s); // [1, 2, 3]
  • 1
  • 2
  • 3

5. has()

has(): 查询Set实例是否存在某元素(返回布尔值):

const s = new Set();s.add(1).add(2).add(3);s.has(1); // true
  • 1
  • 2
  • 3

6. delete()

delete(): 删除Set实例中某个元素(返回布尔值):

const s = new Set();s.add(1).add(2);s.delete(1);Array.from(s); // [2]
  • 1
  • 2
  • 3
  • 4

7. clear()

clear(): 清空Set实例:

const s = new Set();s.add(1).add(2).add(3);Array.from(s); // [1, 2, 3]s.clear();Array.from(s); // []
  • 1
  • 2
  • 3
  • 4
  • 5

8. 迭代

keys():返回键名;
values(): 返回键值;
entries(): 返回键值对;
键名=键值

const s = new Set();s.add(1).add(2).add(3);Array.from(s.keys()); // [1, 2, 3]Array.from(s.values()); // [1, 2, 3]Array.from(s.entries()); // [[1, 1], [2, 2], [3, 3]]
  • 1
  • 2
  • 3
  • 4
  • 5
for-of:
const s = new Set();s.add(1).add(2).add(3);for (const i of s) {	console.log(i);}// 1// 2// 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
forEach
const s = new Set();s.add(1).add(2).add(3);s.forEach((value, key) => console.log(key + ' : ' + value));// 1 : 1// 2 : 2// 3 : 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发