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/