当前位置: 首页 > news >正文

ES6——数组扩展之Set数组

在ES6(ECMAScript 2015)中,JavaScript的Set对象提供了一种存储任何值唯一性的方式,类似于数组但又不需要索引访问。这对于需要确保元素唯一性的场景非常有用。Set对象本身并不直接提供数组那样的方法来操作数据(例如mapfilterreduce等),但是可以通过将Set转换成数组来实现这些操作。下面是一些常用的数组方法及其在Set上的应用方式:

方法描述

Set

Set转换成数组

map()

Set中的每个元素应用一个函数,可以将Set转换为数组后使用map()方法。

filter()

使用filter()方法可以筛选出满足条件的元素。

reduce()

reduce()方法可以用来将Set中的元素组合起来,例如求和。

find() 、 findIndex()

虽然原生Set没有直接提供这些方法,但可以通过转换为数组来使用。

some() 、 every()

这些方法可以用来检查Set中的元素是否满足特定条件。

使用场景和示例代码: 

1. 将Set转换为数组

const set = new Set([1, 2, 3, 4]);// 使用扩展运算符
const array1 = [...set];// 使用Array.from()
const array2 = Array.from(set);

2. map() 方法

const set = new Set([1, 2, 3, 4]);
const mappedArray = Array.from(set).map(x => x * 2);
console.log(mappedArray); // [2, 4, 6, 8]

3. filter() 方法

const set = new Set([1, 2, 3, 4, 5]);
const filteredArray = Array.from(set).filter(x => x > 3);
console.log(filteredArray); // [4, 5]

4. reduce() 方法

const set = new Set([1, 2, 3, 4]);
const sum = Array.from(set).reduce((acc, current) => acc + current, 0);
console.log(sum); // 10

5. find() 和 findIndex() 方法

const set = new Set(['apple', 'banana', 'cherry']);
const foundItem = Array.from(set).find(item => item === 'banana');
console.log(foundItem); // 'banana'

6. some() 和 every() 方法

const set = new Set([1, 2, 3, 4]);
const hasEven = Array.from(set).some(x => x % 2 === 0); // 检查是否有偶数
console.log(hasEven); // true

补充

数组去重:
var arr = [1,1,2,2,3,3,1,4,4];
[...new Set(arr)]; // [1, 2, 3, 4]
Array.from(new Set(arr)); // [1, 2, 3, 4]
[...new Set('abababcd')].join(''); // "abcd" 可以字符串去重
new Set('Hello world'); //["Hello","world"]

数组交集:

var a = new Set([1, 2, 3, 4]);
var b = new Set([4, 3, 2, 5]);
var intersect = new Set([...a].filter(x => b.has(x))); // {2, 3, 4}

数组并集:

var a = new Set([1, 2, 3, 4]);
var b = new Set([4, 3, 2, 5]);
var union = new Set([...a, ...b]); // {1, 2, 3, 4, 5}

数组差集:

var a = new Set([1, 2, 3, 4]);
var b = new Set([4, 3, 2, 5]);
var difference = new Set([...a].filter(x => !b.has(x))); // {1, 5}

 

小结:

[...new Set()]‌ 是一种在JavaScript中用于去重和展开集合的操作。具体来说,new Set() 创建一个新的 Set 对象,该对象存储的元素是唯一的,不会出现重复的值。通过使用扩展运算符(...),可以将 Set 对象中的元素展开成数组形式。

相关文章:

  • [TIP] Ubuntu 22.04 配置多个版本的 GCC 环境
  • 第7篇:中间件全链路监控与 SQL 性能分析实践
  • 如何理解 IP 数据报中的 TTL?
  • 高效Excel合并拆分软件
  • 论文阅读:HySCDG生成式数据处理流程
  • 《ERP原理与应用教程》第3版习题和答案
  • MySQL安装与配置详细讲解
  • LINUX 66 FTP 2 ;FTP被动模式;FTP客户服务系统
  • Nestjs框架: nestjs-schedule模块注册流程,源码解析与定时备份数据库
  • Aspose.PDF 限制绕过方案:Java 字节码技术实战分享(仅供学习)
  • 飞云智能波段主图+多空短线决策副图指标,组合操盘技术图文解说
  • 预训练语言模型T5-11B的简要介绍
  • 【Dv3Admin】系统视图菜单字段管理API文件解析
  • 如何以 9 种方式将照片从手机传输到笔记本电脑
  • 智谱清言沉思智能体,天工智能体,agenticSeek等AI Agent测试记录
  • Linux缓冲区与glibc封装:入门指南
  • 2025年全国青少年信息素养大赛 scratch图形化编程挑战赛 小高组初赛 真题详细解析
  • 【更新至2024年】2000-2024年上市公司财务困境MertonDD模型数据(含原始数据+结果)
  • Shopify 主题开发:店铺品牌色在主题中的巧妙运用
  • Oracle 用户名大小写控制
  • ie8打不开建设银行网站/黄冈网站推广软件费用是多少
  • 网站的优点/站长域名查询
  • 常熟公司做网站/站长之家字体
  • 凯里建设局网站/长沙百家号seo
  • 2019年建设什么网站好/seo搜索优化怎么做
  • 铜陵app网站做招聘/优化网站