This article describes the usage of Symbol, Set and Map in ES6. Share it for your reference, as follows:
Symbol
It is ES6 that introduces a new primitive data type that represents a unique value. It is the seventh data type of the JavaScript language. The first six are: undefined, null, Boolean, String, Number, and Object;
Values are generated by Symbol function and can be used as the object's attribute name, ensuring that they will not conflict with other attribute names;
let s = Symbol(); typeof s // symbol
ps: The above code indicates that a Symbol variable is created. It is worth noting that the new command cannot be used before the Symbol function, otherwise an error will be reported. That is to say, Symbol is a primitive value, not an object, and attributes cannot be added;
The function can accept a string as a parameter to represent a description of the Symbol instance, which is mainly used to distinguish different Symbol variables;
let s1 = Symbol('a'); let s2 = Symbol('b'); () // 'Symbol(a)' () // 'Symbol(b)'
ps: The parameters of the Symbol function only represent the description of the current Symbol value, so the return values of the Symbol function with the same parameters are not equal.
let s1 = Symbol('a'); let s2 = Symbol('a'); s1 === s2 //false
Values cannot be computed with other types of values, but can be converted to boolean values, but cannot be converted to numeric values;
let s = Symbol(); s + '2' // Cannot convert a Symbol value to a string Boolean(s) // true !s // false
5. The attribute name used for the object can ensure that the attributes with the same name will not appear. It is very useful for an object to be composed of multiple modules and can prevent a certain key from being accidentally rewritten or overwritten; it is worth noting that when the Symbol value is used as the object attribute name, the dot operator cannot be used because the dot operator is followed by a string;
let s = Symbol(); let obj = {}; obj[s] = 'hello world'; //orlet obj = { [s] : 'hello world' } // undefined obj[s] // hello world
As the attribute name, it will not be traversed by conventional methods, that is, the attribute will not appear in the for...in, for...of loop, nor will it be returned by (), (), (), (). However, it is not a private property. You can use a method to obtain all Symbol attribute names of the specified object;
var obj = {}; var a = Symbol('a'); var b = Symbol('b'); obj[a] = 'Hello'; obj[b] = 'World'; = 'Mine'; for( let key in obj ){ (key) // c } var objectSymbols = (obj); (objectSymbols) // [Symbol(a), Symbol(b)]
The method takes a string as a parameter and then searches for any Symbol value with that parameter as its name. If so, return this Symbol value, otherwise, create and return a Symbol value with the string as its name; unlike Symbol(), () does not return a new Symbol type value every time it is called, but will first check whether the given key already exists. If it does not exist, a new value will be created. Symbol() will return 3 different Symbol values each time;
("name") === ("name") // true Symbol("name") === Symbol("name") // false
The method returns a registered Symbol type value key, and the Symbol() method has no registration mechanism;
var s1 = ("name"); (s1) // "name" var s2 = Symbol("name"); (s2) // undefined
ps: The name registered for the Symbol value is in the global environment, and the same value can be obtained in different iframes or service workers.
Set and Map
1.ES6 provides a new data structure Set. It is similar to an array, but the values of the members are unique and have no duplicate values. It itself is a constructor used to generate the Set data structure.
let s = new Set([1,2,3,4,5,2,2,3,5]); s // [1,2,3,4,5]
2. You can use the add(key) method to add elements to the Set. You can add them repeatedly, but there will be no effect. It is worth noting that when adding values to the Set, there will be no type conversion, that is, 5 and "5" are two different values, but within the Set, the two NaNs are equal.
let s = new Set([1,2,3]); (4) //[1,2,3,4] (4) //[1,2,3,4] (5) //[1,2,3,4,5] ('5') //[1,2,3,4,5,"5"] (NaN) //[1,2,3,4,5,"5",NaN] (NaN) //[1,2,3,4,5,"5",NaN]
3. It can use the feature of Set data not duplicate to provide a new array deduplication method.
// Remove duplicate members of the array [...new Set(array)] [...new Set([1,2,2,3,3,4,5,5])] //[1,2,3,4,5]
Common operating methods are:
add(value): add a certain value and return the Set structure itself.
delete(value): Delete a value and return a boolean value to indicate whether the deletion is successful.
has(value): Returns a boolean value indicating whether the value is a member of Set.
clear(): Clear all members, no return value.
(1).add(2).add(2); // Note that 2 has been added twice // 2 (1) // true (2) // true (3) // false (2); (2) // false
An instance of a structure has four traversal methods that can be used to traverse members.
keys(): Returns the key name traverser
values(): Returns the key value traverser
entries(): Returns the traverser of key-value pairs
forEach(): Use the callback function to traverse each member
It should be pointed out that the traversal order of Set is the insertion order. This feature is sometimes very useful, such as using Set to save a list of callback functions, which can ensure that it is called in the order of addition when called.
let set = new Set(['red', 'green', 'blue']); for (let item of ()) { (item); } // red // green // blue for (let item of ()) { (item); } // red // green // blue for (let item of ()) { (item); } // ["red", "red"] // ["green", "green"] // ["blue", "blue"]
6.ES6 provides a Map data structure, which is similar to an object and is also a collection of key-value pairs. However, the scope of "key" is not limited to strings. Various types of values (including objects) can be regarded as keys, which is a more complete Hash structure implementation. If you need a "key-value pair" data structure, Map is more suitable than Object;
Common operating methods are:
set(key,val): add a certain value and return the Map structure itself.
get(key): Read a key, if the key is unknown, return undefined
delete(key): Delete a key, return a boolean value, indicating whether the deletion is successful.
has(key): Returns a boolean value indicating whether the value is the key of Map.
clear() : Clear all members, no return value.
const m = new Map(); const o = { str : 'Hello World'}; (o, 'content') (o) // "content" (o) // true (o) // true (o) // false
8. Map structure treats it as the same key only if it is a reference to the same object.
const map = new Map(); const k1 = ['a']; const k2 = ['a']; (k1, 111).set(k2, 222); (k1) // 111 (k2) // 222
The above example shows that the key of Map is actually bound to the memory address. As long as the memory address is different, it is regarded as two keys. Because k1 and k2 are two different objects and are placed in different memory addresses, Map is regarded as different keys.
Structure native provides three traverser generation functions and one traversal method.
keys(): Returns the traverser that returns the key name.
values(): Returns the key value traverser.
entries(): Returns the traverser for all members.
forEach(): Iterates through all members of the Map.
ps: The traversal order of Map is the insertion order. I won’t have an example here. Please practice it yourself.
10. You can use the extension operator (...) to convert the Map into an array. In turn, pass the array into the Map constructor and convert it to a Map.
//Map to arrayconst map = new Map(); ('name' , 'hello').set({},'world'); [...map] //[["name","hello"],[{},"world"]] //Array to Mapconst map = new Map([["name","hello"],[{},"world"]]); map // {"name" => "hello", Object {} => "world"}
Interested friends can use itOnline HTML/CSS/JavaScript code running tool:http://tools./code/HtmlJsRunTest the above code running effect.
For more information about JavaScript, please view the topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage》
I hope this article will be helpful to everyone's JavaScript programming.