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/