JavaScript 中的集合与数组:何时使用哪个?
来源:dev.to
2025-01-23 17:28:10
0浏览
收藏
文章小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《JavaScript 中的集合与数组:何时使用哪个?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
javascript 提供了两种强大的数据结构来存储集合:set 和 array。虽然两者都可以存储多个值,但它们独特的特性使它们更适合不同的场景。让我们探讨一下您何时以及为何会选择其中之一。
1. 默认的唯一值
set 最显着的特点是它自动处理重复项。
// arrays allow duplicates const arr = [1, 2, 2, 3, 3, 4]; console.log(arr); // [1, 2, 2, 3, 3, 4] // sets automatically remove duplicates const set = new set([1, 2, 2, 3, 3, 4]); console.log([...set]); // [1, 2, 3, 4] // removing duplicates from an array using set const uniquearray = [...new set(arr)]; console.log(uniquearray); // [1, 2, 3, 4]
2. 元素检查性能
set 提供更快的查找时间来检查元素是否存在。
const largearray = array.from({ length: 1000000 }, (_, i) => i);
const largeset = new set(largearray);
// array lookup
console.time('array includes');
console.log(largearray.includes(999999));
console.timeend('array includes');
// set lookup
console.time('set has');
console.log(largeset.has(999999));
console.timeend('set has');
// set is significantly faster because it uses hash table internally
3. 可用方法和操作
数组提供了更多内置的数据操作方法,而集合则专注于唯一性管理。
// array methods const arr = [1, 2, 3, 4, 5]; arr.push(6); // add to end arr.pop(); // remove from end arr.unshift(0); // add to beginning arr.shift(); // remove from beginning arr.splice(2, 1, 'new'); // replace elements arr.slice(1, 3); // extract portion arr.map(x => x * 2); // transform elements arr.filter(x => x > 2); // filter elements arr.reduce((a, b) => a + b); // reduce to single value // set methods const set = new set([1, 2, 3, 4, 5]); set.add(6); // add value set.delete(6); // remove value set.has(5); // check existence set.clear(); // remove all values
4. 订单和索引访问
数组维护插入顺序并提供基于索引的访问,而集合仅维护插入顺序。
// array index access const arr = ['a', 'b', 'c']; console.log(arr[0]); // 'a' console.log(arr[1]); // 'b' arr[1] = 'x'; // direct modification // set has no index access const set = new set(['a', 'b', 'c']); console.log([...set][0]); // need to convert to array first // no direct index modification possible
5. 内存使用
集合通常比数组使用更多的内存,但提供更快的查找速度。
// memory comparison (rough example)
const numbers = array.from({ length: 1000 }, (_, i) => i);
// array memory
const arr = [...numbers];
console.log(process.memoryusage().heapused);
// set memory
const set = new set(numbers);
console.log(process.memoryusage().heapused);
// set typically uses more memory due to hash table structure
6. 常见用例
何时使用数组:
// 1. when order and index access matters const playlist = ['song1.mp3', 'song2.mp3', 'song3.mp3']; const currenttrack = playlist[currentindex]; // 2. when you need array methods const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(x => x * 2); const sum = numbers.reduce((a, b) => a + b, 0); // 3. when duplicates are acceptable or desired const votes = ['yes', 'no', 'yes', 'yes', 'no']; const yesvotes = votes.filter(vote => vote === 'yes').length;
何时使用集合:
// 1. when tracking unique values
const uniquevisitors = new set();
function logvisitor(userid) {
uniquevisitors.add(userid);
console.log(`total unique visitors: ${uniquevisitors.size}`);
}
// 2. for quick lookup operations
const allowedusers = new set(['user1', 'user2', 'user3']);
function checkaccess(userid) {
return allowedusers.has(userid);
}
// 3. for removing duplicates
function getuniquehashtags(posts) {
const uniquetags = new set();
posts.foreach(post => {
post.hashtags.foreach(tag => uniquetags.add(tag));
});
return [...uniquetags];
}
集合和数组之间的转换
您可以在需要时轻松在集合和数组之间进行转换。
// Array to Set const arr = [1, 2, 2, 3, 3, 4]; const set = new Set(arr); // Set to Array - three methods const back1 = [...set]; const back2 = Array.from(set); const back3 = Array.from(set.values()); // Useful for array deduplication const deduped = [...new Set(arr)];
结论
需要时选择数组:
- 基于索引的访问
- 丰富的数组方法(map、reduce、filter等)
- 重复值
- 内存效率
- 传统迭代模式
需要时选择设置:
- 仅限唯一值
- 快速查找操作
- 简单的添加/删除操作
- 维护独特项目的列表
- 快速重复数据删除
请记住,您随时可以在需要时在两种类型之间进行转换,因此请选择最适合您当前需求的一种。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《JavaScript 中的集合与数组:何时使用哪个?》文章吧,也可关注golang学习网公众号了解相关技术文章。
版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
交大O1医疗探索:延长AI思考时间,解锁复杂推理诊断
- 上一篇
- 交大O1医疗探索:延长AI思考时间,解锁复杂推理诊断
- 下一篇
- 电脑如何清除多余的账户信息-清除多余的账户信息的方法
查看更多
最新文章
-
- 文章 · 前端 | 1小时前 |
- TypeScript catch 变量为 unknown 时怎样安全处理
- 478浏览 收藏
-
- 文章 · 前端 | 1小时前 | css · CSS 滚动条 Overflow scrollbar-gutter 布局跳动
- CSS scrollbar-gutter 怎样避免滚动条出现时布局横向跳动
- 417浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- TypeScript satisfies 怎样校验对象又保留字面量类型
- 162浏览 收藏
-
- 文章 · 前端 | 1小时前 | css · CSS 锚点定位 anchor-name position-area position-anchor 浮层定位
- CSS 锚点定位怎样让浮层跟随触发元素
- 262浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端怎样把非关键任务放到空闲时间
- 458浏览 收藏
-
- 文章 · 前端 | 1小时前 | 前端 · 性能监控 · javascript · 浏览器API · 静态资源 前端性能 PerformanceObserver PerformanceResourceTiming 资源等待时间
- 前端怎样统计静态资源等待时间
- 215浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端组件尺寸变化怎样避免循环更新
- 389浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端怎样观察动态节点并及时断开监听
- 479浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端怎样用 Web Locks 协调多标签页任务
- 329浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端多个标签页怎样同步登录状态变化
- 243浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端 Request 读取一次后怎样再次发送
- 301浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 前端怎样合并多个取消信号
- 490浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 511次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 571次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 597次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 549次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 365次使用
查看更多
相关文章
-
- JavaScript函数定义及示例详解
- 2025-05-11 502浏览
-
- 智能体安全引领产业升级——国内AI安全产品市场深度分析
- 2026-08-21 501浏览
-
- CSS变量简化按钮悬停效果技巧
- 2026-05-31 501浏览
-
- JavaScript符号类型详解与应用
- 2026-05-31 501浏览
-
- HTML剪贴板复制粘贴怎么用
- 2026-05-26 501浏览
