让我们了解Set及其在JavaScript中的独特功能

by Asif Norzai

通过Asif Norzai

让我们了解Set及其在JavaScript中的独特功能🎲 (Let's learn about Set and its unique functionality in JavaScript 🎲)

设置🎲 (SET 🎲)

ES2015/ES6 gave us a lot of useful tools and features, but one that stands out the most for me is Set. It’s not used to its full potential. I hope to convince you of its worth with this article, so that you can reap the full benefits of this beautiful utility.

ES2015 / ES6为我们提供了许多有用的工具和功能,但对我来说最引人注目的是Set。 它没有充分发挥其潜力。 我希望通过本文使您相信它的价值,以便您可以从这个漂亮的实用程序中获得全部好处。

那么,Set是什么? (So what is Set, you ask?)

“The Set object lets you store unique values of any type, whether primitive values or object references.”, MDN.

MDN: “使用Set对象可以存储任何类型的唯一值,无论是原始值还是对象引用。”

Set removes duplicate entries.

Set删除重复的条目。

基本功能 🔥 (Basic Functionality 🔥)

Whenever you want to use Set, you have to initialize it using the new keyword and pass in an initial iterable data, leave it blank or null.

每当要使用Set ,都必须使用new关键字对其进行初始化,并传入初始的可迭代数据,将其保留为blank或null

// All valid ways to initialize a set
const newSet1 = new Set();
const newSet2 = new Set(null);
const newSet3 = new Set([1, 2, 3, 4, 5]);

设置实用程序/方法 🚙 (Set utilities/methods 🚙)

add, like its name suggests, adds new entries to the newly initialized Set const. If at any time a duplicate value gets added to the set, it will be discarded using strict equality.

add 顾名思义,它将新条目添加到新初始化的Set const中。 如果在任何时候将重复值添加到集合中,则将使用strict equality将其丢弃。

const newSet = new Set();newSet.add("C");
newSet.add(1);
newSet.add("C");// chain add functionality
newSet.add("H").add("C");newSet.forEach(el => {console.log(el);// expected output: C// expected output: 1// expected output: H
});

has checks to see if the value that you pass in exists in the newSet const. If the value does exist, it will return the Boolean true, and it’ll return false if it doesn’t

has 检查传入的值是否存在于newSet const中。 如果该值确实存在,它将返回布尔值true ,如果不存在则返回false

const newSet = new Set(["A", 2, "B", 4, "C"]);console.log(newSet.has("A"));
// expected output: trueconsole.log(newSet.has(4));
// expected output: trueconsole.log(newSet.has(5));
// expected output: false

clear & delete are two of the most important functionalities of Set if you want to either remove all entries or delete a specific value.

clear delete 如果要删除所有条目或删除特定值,则Set是两个最重要的功能。

const newSet = new Set(["A", 2, "B", 4, "C"]);newSet.delete("C");
// expected output: truenewSet.delete("C");
// expected output: falsenewSet.size
// expected output: 4newSet.clear();
// expected output: undefinednewSet.size
// expected output: 0

keys and values both have the same functionality, which is weird if you think about how they behave with JS objects. They both return an iterator object. This means you can access the .next() method on it to get its value.

keys values都具有相同的功能,如果您考虑它们在JS对象中的行为,这将很奇怪。 它们都返回一个iterator对象。 这意味着您可以访问它的.next()方法以获取其值。

const newSet = new Set(null);newSet.add("Apples");
newSet.add(12);let iterator = newSet.keys();  // same as newSet.values();console.log(iterator.next().value);
// expected output: Applesconsole.log(iterator.next().value);
// expected output: 12console.log(iterator.next().value);
// expected output: undefined

放在一起 (Bring it all together)

Let’s create a simple function for a hacker party. The function adds users to the list only if they have the approval of an admin. So you have to have an admin’s name with your entry, which is secret (not in this article, though). At the end of the program, it will say who is invited.

让我们为黑客聚会创建一个简单的功能。 该功能仅在获得管理员批准的情况下将用户添加到列表中。 因此,您必须在条目中输入管理员名称,这是秘密的(不过,本文中没有)。 在计划结束时,会说出邀请者。

// The Admins
const allowedAdminUsers = new Set(["Naimat", "Ismat", "Azad"]);// An empty Set, stored in memory
const finalList = new Set();// A function to add users to permission list
const addUsers = ({user, admin}) => {// Check to see if the admin is the admin // list and that the user isn't already in the setif(allowedAdminUsers.has(admin) && !finalList.has(user)) {// Return the users list at the endreturn finalList.add(user);}// Console.log this message if the if the condition doesn't passconsole.log(`user ${user} is already in the list or isn't allowed`); 
};// Add some entries
addUsers({user: "Asep", admin: "Naimat"});
addUsers({user: "John", admin: "Ismat"});// Lets add John again and this time that inner function console error will be shown
addUsers({user: "John", admin: "Azad"});const inviationList = [...finalList].map(user => `${user} is invited`);console.log(inviationList);
// Expected output:  ["Asep is invited", "John is invited"]

That’s enough functionality for us to use Set today in our projects. 🎓

这足以让我们在项目中使用Set。 🎓

Before you go: if you liked this post, follow me on here and also on Twitter, where I post and retweet web-related content.

开始之前 :如果您喜欢这篇文章,请在这里以及在Twitter上关注我,我在其中发布和转发与Web相关的内容。

翻译自: https://www.freecodecamp.org/news/lets-learn-about-set-and-its-unique-functionality-in-javascript-5654c5c03de2/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393584.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言第二次博客作业---分支结构

一、PTA实验作业 题目1:计算分段函数[2] 本题目要求计算下列分段函数f(x)的值: 1.实验代码 double x,result;scanf("%lf",&x);if(x>0){resultsqrt(x);}else{resultpow(x1,2)2*x1/x;}printf("f(%.2f) %.2f",x,result); 2 设计…

oracle+数据到+mysql数据库乱码_oracle数据mysql数据库乱码

{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":4,"count":4}]},"card":[{"des":"阿里云数据库专家保驾护航,为用户…

ajax 不执行

1、get形式访问: 一个相同的URL 只有一个结果,所以 第二次访问的时候 如果 URL字符串没变化 浏览器是 直接拿出了第一次访问的结果,post则不会 解决办法: 1、urlnew Date(); (每次访问时url不同) 2、 type : get,   …

leetcode870. 优势洗牌(贪心算法)

给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。 返回 A 的任意排列,使其相对于 B 的优势最大化。 示例 1: 输入:A [2,7,11,15], B [1,10,4,11] 输出:[2,11,…

Mysql中行转列和列转行

一、行转列即将原本同一列下多行的不同内容作为多个字段,输出对应内容。建表语句DROP TABLE IF EXISTS tb_score; CREATE TABLE tb_score( id INT(11) NOT NULL auto_increment, userid VARCHAR(20) NOT NULL COMMENT 用户id, subject VARCHAR(20) COMMENT…

OSChina 周四乱弹 ——妹子喜欢的是程序员 这是标准……

2019独角兽企业重金招聘Python工程师标准>>> Osc乱弹歌单(2017)请戳(这里) 【今日歌曲】 一叶孤鸿 :分享Nanaka的单曲《いのちの名前(Cover 木村弓)》 《いのちの名前(C…

阿里薪资谈判技巧_如何像专业人士一样处理技术职业中的薪资谈判

阿里薪资谈判技巧by Aline Lerner通过艾琳勒纳(Aline Lerner) 如何像专业人士一样处理技术职业中的薪资谈判 (How to handle salary negotiations in your tech career like a pro) 确切地谈薪水时要说些什么 (Know exactly what to say when negotiating your salary) There …

xp系统sql服务器怎么找,SQL文件在winxp系统下怎么打开

很多用户不知道SQL文件是什么?SQL文件怎么打开?我们存储数据时候经常会遇到SQL文件,如果你不知道WinXP系统SQL文件是什么以及怎么打开的话,那就赶紧看看小编整理的以下文章内容吧!SQL文件是什么?学习编程的同学可能都知道SQL是一种高级的非过程化的编…

Silverlight 设计器加载错误

每次打开silverlight页面出如下错误 然后设计器不能将页面加载出来 最后找了蛮多资料的 感觉这个原因有可能:“控制面板的添加删除程序那里,选中Microsoft Silverlight,看看他的版本,是否与所装的SDK的版本号一致。就算两个版本号…

mysql索引优化实际例子_MySQL索引优化的实际案例分析

Order by desc/asc limit M是我在mysql sql优化中经常遇到的一种场景,其优化原理也非常的简单,就是利用索引的有序性,优化器沿着索引的顺序扫描,在扫描到符合条件的M行数据后,停止扫描;看起来非常的简单&am…

leetcode441. 排列硬币(二分查找)

你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。 给定一个数字 n,找出可形成完整阶梯行的总行数。 n 是一个非负整数,并且在32位有符号整型的范围内。 示例 1: n 5 硬币可排列成以下几行: …

【洛谷 P2051】 [AHOI2009]中国象棋(DP)

题目链接 首先想到状压dp,但是\(n,m\)高达100,怎么压? 容易发现,每行每列最多两个象棋,否则就直接gg了。 一个巧妙的设置状态的方式是,只需要记录到当前行有多少列是放了1个炮和2个炮。 然后每一行有3种选择…

循环 直到 python_如果您在Python中存在慢循环,则可以对其进行修复……直到无法解决为止...

循环 直到 pythonby Maxim Mamaev马克西姆马马耶夫(Maxim Mamaev) Let’s take a computational problem as an example, write some code, and see how we can improve the running time. Here we go.让我们以一个计算问题为例,编写一些代码,看看如何改…

阿里云视频点播解决方案使用教程

2019独角兽企业重金招聘Python工程师标准>>> 课程介绍 视频点播(ApsaraVideo for VoD,简称VoD)是集视频音视频采集、编辑、上传、自动化转码处理、媒体资源管理、分发加速于一体的一站式音视频点播解决方案。 产品详情&#xff1a…

云服务器安装操作系统后如何连接,服务器如何安装操作系统

服务器如何安装操作系统 内容精选换一换如果您需要使用毕昇编译器,则需要先在服务端安装毕昇编译器。毕昇编译器基于开源LLVM开发,并进行了优化和改进,同时将flang作为默认的Fortran语言前端编译器,是针对鲲鹏平台的高性能编译器。…

换行符

非原创windows保留\r\n作为换行符的原因: 回车键为什么叫回车键,大家有想过没有,字面意思是回去的车子。 第一台打印机,每一行打印完了之后在打印第二行之前,这个喷墨的玩意儿需要先回到这一行的行首,这叫回…

leetcode剑指 Offer 53 - II. 0~n-1中缺失的数字(二分查找)

一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 示例 1: 输入: [0,1,3] 输出: 2 代码 class Solution {public…

python 0基础起步学习day2

元组:戴上了枷锁的列表 元组是不可改变的,元组是不能随意改变内部的元素的 元组和列表很像,它可以看成是不可修改的列表 所以创建元祖逗号是关键 因为(8,)是元组,这里*就不再是乘号,而是重复拷贝符【重复操作符】 直接…

react中的状态机_在基于状态图的状态机上使用React的模式

react中的状态机by Shawn McKay肖恩麦凯(Shawn McKay) 在基于状态图的状态机上使用React的模式 (Patterns for using React with Statechart-based state machines) Statecharts and state machines offer a promising path for designing and managing complex state in apps…

android scheme打开天猫,淘宝

直接上代码 Intent intent new Intent(); intent.setAction("android.intent.action.VIEW"); /*String url "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id131259851&spma230r.7195193.1997079397.8.Pp3ZMM&point" "%7B%22…