讓我們了解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.pswp.cn/news/393584.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393584.shtml
英文地址,請注明出處:http://en.pswp.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…