current position:Home>JavaScript ES6 set (set) type* ω *
JavaScript ES6 set (set) type* ω *
2022-04-29 10:32:35【XianZhe_】
Javascript ES6 aggregate (SET) type * ω *
List of articles
One 、 aggregate
aggregate (Set), yes ES6 New data type in , This is the same as the concept of set in Mathematics .
In the interpretation of the JS Before the collection of , I think it's still necessary to review the main categories in the mathematical set first : Combine , intersection , Difference set
JavaScript Set properties
- Set yes ES6 New data structure provided , Allow any data type to be stored .
- Natural weight loss , Each element is unique , Different from each other , This is also the main feature of the set .
- Its elements can be iterated according to the insertion order .
Brief overview : A collection is an unordered and non repeating data type
Two 、 Take advantage of its de duplication
As mentioned above , The collection is born to lose weight , Then we can use the de duplication of sets to do something
Array weight removal :
Zhang San used a cover up , Made several fake Zhang San , Let's see how Miss Luo treats Zhang San// const name = [' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Luo Xiang '] let names = Array(10).fill(" Zhang San ", 0, 10) // You can also add multiple sheets in this way names.push(" Luo Xiang "); names = [...new Set(names)] console.log(names)
[" Zhang San ", " Luo Xiang "]
Is that so? , You can crack Zhang San's deception by using a collection , Find out the only Zhang San
Next, let's look at an application of de duplication , Don't repeat the lottery
const res = new Set(); const names = [" Zhang San ", " Li Si ", " Xiao Ming ", " Li Hua ", " John ", "Jone", "Mark", "Bill", "PrettyGirl"]; while (res.size < 3) { res.add(names[Math.abs(parseInt(Math.random() * 8))]) } console.log(res)
The program logic : Using the random Pick a name at random , Add this name to the collection , If it is repeated, no adding operation will be performed , The circulation condition is to judge whether the number of people in the collection is less than 3
3、 ... and 、 iteration Set
Before explaining the following , It is necessary to understand the data structure in the collection .
First of all, we should understand that the traditional index method cannot extract the set data .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]); for (let i=0; i < vegetable.size; i++) { // Unable to remove , The output is undefined console.log(vegetable[i]) }
Because the collection has no index , Use for in The value of the loop is also unavailable .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]); // Loop not executed for (let key in vegetable) { console.log(key) }
Only use for of Take values in a circular way , To have results
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]); for (let value of vegetable) { console.log(value) }
Green vegetables radish Apple Banana potatoes a mandarin orange
Four 、 Methods for collecting instance objects
1)、Set.prototype.add(value)
stay Set Add an element at the end of the object , And return to the Set object .
const vegetable = new Set([" Green vegetables ", " radish "]);
vegetable.add(" Apple ");
console.log(vegetable);
The... Will be returned according to the Set The principle of objects , Can be achieved for this Set Chain operation of object .
const vegetable = new Set([" Green vegetables ", " radish "]);
vegetable.add(" Apple ").add(" Banana ").add(" potatoes ").add(" a mandarin orange ");
console.log(vegetable);
{" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "}
2)、Set.prototype.clear()
remove Set All elements in the object .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
vegetable.clear();
console.log(vegetable); // The collection is empty after emptying
3)、Set.prototype.delete(value)
Remove the element in the collection equal to this value , And return whether the deletion was successful .
Before deleting , The program will execute first Set.prototype.has(value)
, Determine whether the element to be deleted exists , If the element exists , After deleting the element, it returns true
, Otherwise return to false
.
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
const r1 = vegetable.delete(" radish ");
const r2 = vegetable.delete(" Bro ");
console.log(r1, r2);
true false
4)、Set.prototype.entries()
Returns a new iterator object , This object contains the values of all elements in the collection object in insertion order [value, value]
Array , Because only values exist in a set , So the elements in the array are equal .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let [key, value] of vegetable.entries()) {
console.log(key, value);
}
5)、Set.prototype.forEach(callbackFn[, thisArg])
In insertion order , by Set Every value in the object is called once callBackFn. If provided thisArg Parameters , In callback this It's going to be this parameter .
The parameters are as follows :
- callbackFn: Callback function executed for each element in the collection , This function takes three parameters :
- currentValue: The element being manipulated .
- currentKey: Because the collection has no index , therefore currentKey This element is also represented by .
- set: Call current
forEach
Method .
- thisArg: During the execution of callback function this value .
Demo code :
vegetable.forEach(function (currentValue, currentKey, set) {
console.log(currentValue, currentKey, set)
})
Green vegetables Green vegetables Set(6){' Green vegetables ', ' radish ', ' Apple ', ' Banana ', ' potatoes ',…}
radish radish Set(6){' Green vegetables ', ' radish ', ' Apple ', ' Banana ', ' potatoes ',…}
......
6)、Set.prototype.has(value)
Returns a Boolean value , Indicates that the value is in Set Whether it exists in .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
console.log(vegetable.has(" potatoes ")); // true
console.log(vegetable.has(" Bean soil ")); // false
7)、Set.prototype.keys()
Because only values exist in a set , And values()
In the same way , Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let item of vegetable.keys()) {
console.log(item)
}
Green vegetables
radish
Apple
Banana
potatoes
a mandarin orange
8)、Set.prototype.values()
Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object .
const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let item of vegetable.values()) {
console.log(item)
}
Green vegetables
radish
Apple
Banana
potatoes
a mandarin orange
9)、Set.prototype[@@iterator]()
Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object . Usage and Set.prototype.keys()
and Set.prototype.values()
The method is the same .
for (let item of vegetable[Symbol.iterator]()) {
console.log(item)
}
Green vegetables
radish
Apple
Banana
potatoes
a mandarin orange
actually ,Set.prototype.keys()
and Set.prototype.values()
Method return is also an iterator object , The data content is consistent . Use next()
Methods observe .
const iterator = vegetable[Symbol.iterator]()
console.log("iterator:", iterator.next())
console.log("iterator:", iterator.next())
const keys = vegetable.keys()
console.log("keys:", keys.next())
console.log("keys:", keys.next())
const values = vegetable.values()
console.log("values:", values.next())
console.log("values:", values.next())
5、 ... and 、 Extended set method
1)、 Add methods to the collection prototype
/** * to update (update) aggregate , Add from others All elements in , Inspiration comes from Python * @param others: Iteratable object * @return {Set<any>} After adding results, the collection */
Set.prototype.update = function (others) {
if (others.constructor === Set) {
for (let i of others) {
this.add(i);
}
} else {
for (let i = 0; i < others.length; i++) {
this.add(others[i]);
}
}
return this
}
/** * Update collection , Removal also exists in others The elements in , That is, remove the elements that exist in both collections * @param elems Another set that needs to be updated * @return {Set<any>} Return to the new set */
Set.prototype.difference_update = function (elems) {
for (let e of elems) {
if (this.has(e)) {
this.delete(e);
} else {
this.add(e);
}
}
return this
}
/** * Returns the difference set method of the set , Inspiration comes from Python * @param set Another set to compare * @returns {Set<any>} Difference set */
Set.prototype.difference = function (set) {
const diff = new Set();
for (let item of set) {
if (!this.has(item)) {
diff.add(item);
}
}
return diff
}
/** * Returns the intersection method of the set , Inspiration comes from Python * @param set Another set to compare * @returns {Set<any>} Intersection set */
Set.prototype.intersection = function (set) {
const common = new Set();
for (let item of set) {
if (this.has(item)) {
common.add(item);
}
}
return common
}
/** * Returns the union method of the set , Inspiration comes from Python * @param set Another set that needs to be merged * @returns {Set<any>} Merge sets */
Set.prototype.union = function (set) {
return this.update(set)
}
/** * Get collection length * @return {number} Length value */
Set.prototype.length = function () {
return this.size;
}
2)、 Inherit
If you want to extend the method of the collection without affecting the original collection constructor , You can extend a collection by inheriting it .
class MySet extends Set {
/** * to update (update) aggregate , Add from others All elements in , Inspiration comes from Python * @param others: Iteratable object * @return {Set<any>} After adding results, the collection */
update(others) {
if (others.constructor === Set) {
for (let i of others) {
this.add(i);
}
} else {
for (let i = 0; i < others.length; i++) {
this.add(others[i]);
}
}
return this
}
/** * Update collection , Removal also exists in others The elements in , That is, remove the elements that exist in both collections * @param elems Another set that needs to be updated * @return {Set<any>} Return to the new set */
difference_update(elems) {
for (let e of elems) {
if (this.has(e)) {
this.delete(e);
} else {
this.add(e);
}
}
return this
}
/** * Returns the difference set method of the set , Inspiration comes from Python * @param set Another set to compare * @returns {Set<any>} Difference set */
difference(set) {
const diff = new Set();
for (let item of set) {
if (!this.has(item)) {
diff.add(item);
}
}
return diff
}
/** * Returns the intersection method of the set , Inspiration comes from Python * @param set Another set to compare * @returns {Set<any>} Intersection set */
intersection(set) {
const common = new Set();
for (let item of set) {
if (this.has(item)) {
common.add(item);
}
}
return common
}
/** * Returns the union method of the set , Inspiration comes from Python * @param set Another set that needs to be merged * @returns {Set<any>} Merge sets */
union(set) {
return this.update(set)
}
length() {
return this.size;
}
}
Reference material
Official documents :
mdn web dos:
Wikipedia Chinese website :
Related blog
copyright notice
author[XianZhe_],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290916526758.html
The sidebar is recommended
- Install and configure nginx in Linux Environment
- Vue dynamically binds attributes and dynamically obtains attribute values
- Summary method of Vue value in key pair mapping
- Vue simply realizes the addition, deletion and modification of each tab page without route jump
- Vue time control common processing
- Vue validation array
- Simple and easy to let you know what AJAX is, even if you are a little white, a rookie can understand it!
- Receive the JSON string from the front end, and summarize the methods of parsing and value taking at the back end
- Solution: httpmessagenotreadableexception: JSON parse error: invalid UTF-8
- Vuetify: install vuetify from scratch
guess what you like
Install CSS from tailwind
Ubuntu 16 wireless network card model query and driver installation, Lenovo g400 bcm43142 network card WiFi
Some color knowledge to understand at the front end
Functional programming of front-end development
A front-end interview question -- implementing an encapsulated Ajax device (promise version)
Dynamic components of angular
Front end written test pit -- JS implicit conversion
Shallow understanding of HTTP
React style modification background invalid
Finding the k-th small element of ordered matrix (dichotomy idea)
Random recommended
- JavaScript functions -- pre parsing, Iife, advanced functions, recursion
- JavaScript object
- How to introduce element plus gracefully in vue3 project on demand
- Component slot Vue js
- How to write game interface style in HTML
- Ask some front-end questions.
- Information | driverless taxi has come to Beijing. Xiaoma Zhixing has been approved to carry out automatic driving service in Beijing
- [taro react] - H5 route configuration cancels # on the route
- Reverse advanced, using ast technology to restore JavaScript obfuscated code
- JavaScript object
- Vue introduces vant / elementul
- JavaScript queue“
- Vue content summary
- vue3. 0
- Small tips: detection of JS font loading failure or completion
- CSS is a box that has been climbing
- Leetcode215 - the kth largest element in the array - quick sort - quick select - template
- CSS adds effect to the four corners of div
- HTTP error 500.19 internal server error occurred in the integration pageoffice of aspnetcore project,
- Front end < TD > what is the word limit of the label
- Construction and development of automatic test platform based on HTTP runner
- Application of RT thread - use RT thread on stm32l051 (v. conclusion of wireless temperature and humidity sensor)
- Expose Dubbo to HTTP service
- Put the front end into the spring cloud project
- Front end learning day 4 - CSS
- Vue URL jump page with parameters
- JavaScript Chapter 13 traversal of arrays and implicit parameters of function methods
- These CSS efficiency improvement skills, you need to know!
- Beijing has opened the pilot of unmanned operation of passenger cars, and the driverless air outlet has arrived
- Test theory series - Test Case elements and design methods Part II
- How to make the peak value of measured output voltage not less than 2V
- Hexo quickly set up its own blog
- Gee synthetic cloudless landsat-8 and sentry-2 data
- Prototype object creation method case JavaScript specific implementation steps
- YAF CLI and HTTP access modes
- Simple HTML + CSS animation web page production DW simple animation web page production
- The correct way for web programmers to make a pink girl series happy birthday blessing web page (HTML + CSS + JS)
- HTML + CSS + JS to make simple animation web pages
- HTML gourmet web page production DW static web page production div + CSS gourmet web page implementation and production
- Programmer 520 Tanabata Valentine's Day confession code HTML + JS + CSS petal photo album web page template programmer confession necessary