This article is about ES6 The third in the series , This paper mainly introduces ES6 New data types 、 data structure , Go to the portal first :

1 The seventh data type Symbol

ES6 A new type of raw data is introduced Symbol, Represents a unique value . It is JavaScript The seventh data type of language , The first six are :Undefined、Null、 Boolean value (Boolean)、 character string (String)、 The number (Number)、 object (Object).

 let s = Symbol();
console.log(typeof s); //"symbol"

Symbol The type variable is passed through Symbol() Method to build ( Out of commission new), In addition, the method can accept a string type parameter as the Symbol Of describe

 let s1 = Symbol('tag');
let s2 = Symbol('tag'); s1 == s2; //false, Parameters are only used as descriptions , Even two of the same description Symbol It's also different

Symbol Type use note :

 let s = Symbol();
"symbol:" + s; // Report errors , Cannot compute with string
s + 2; // Report errors , Cannot compute with string
s1.toString(); //"Symbol(tag)",Symbol It is possible to convert the display to a string type
... // Can be converted to bool

Said so much ,ES6 Introduction in Symbol What is it for ?

Because of any two Symbol It's all unequal , This means that we can use it as the property name of the object , And don't worry about the duplicate attribute name , This is useful in team development , Take a chestnut :

 let attr = Symbol();
// Method 1
let obj = {};
obj[attr] = 'hello'; // Method 2
let obj = {
[attr]: 'hello'
} // Method 3
let obj = {};
Object.defineProperty(a, mySymbol, { value: 'Hello!' }); // The above three ways of defining attributes have the same effect
obj[attr]; //"hello" // Method 4
let obj = {};
obj.attr = 'hello';
obj[attr]; //undefined, Be careful not to use “.” Operator

In addition, through Symbol Functions defined are not And so on , If you want to traverse Symbol Property to use Object.getOwnPropertySymbols To traverse Symbol attribute , Or use a new one APIReflect.ownKeys Traverse all properties ( Include Symbol And other attributes ), Look at examples :

var attr1 = Symbol('a1');
var attr2 = Symbol('a2'); var obj = {
}; for(let attr in obj){
console.log(attr); //name, Traverse only to name attribute
} Object.getOwnPropertySymbols(obj);//[Symbol(a1),Symbol(a2)] Traverse only Symbol attribute Reflect.ownKeys(obj); //[Symbol(a1),Symbol(a2),name], Traverse all properties

2 New data structure Set

Set Data structure is similar to array , The difference lies in Set The inner element is the only one that does not repeat ,Set The function accepts an array ( Or something like an array ) As a parameter , Used to initialize , Can pass add Method add element , Look at the chestnuts :

 //ES6 In the environment
//Set Methods 
//Set - Constructors , Parameter is an array
let arr = [1,2,3,3,4,4];
let s = new Set(arr);//Set{1,2,3,4} //add - Add a value , Return to the structure itself
s.add(5); //Set{1,2,3,4,5}
s.add(2); //Set{1,2,3,4,5}
s.add(6).add(7);//Set{1,2,3,4,5,6,7} //delete - Delete a value , Returns a Boolean value indicating whether the deletion was successful
s.delete(6); //true,Set{1,2,3,4,5,7} //has - Determine whether the value is included , Returns a Boolean value
let ok = s.has(6);//false,Set{1,2,3,4,5,7} //clear - Empty Set
s.clear();//Set{} //Set Properties of
s.size; //0, Unlike arrays set adopt size Get size
s.size; //1

Set The inner element is unique , Therefore, the most intuitive use is array de duplication , Now we can do array de duplication like this :

 function unique(arr){
return [ Set(arr)]; //... Operator reference ES6 series ( Two ) // perhaps return Array.from(new Set(arr));

Set How to define whether the two elements are the same , So let's test that out :

 let s = new Set();
s.add(5); //Set{5}
s.add('5'); //Set{5,'5'}, There is no type conversion , It's through "===" instead of “==” let [n1,n2] = [NaN,NaN];
s.add(n1); //Set{5,'5',NaN}
s.add(n2); //Set{5,'5',NaN}, only one NaN Show in Set Inside NaN They are equal. s.add({}); //Set{5,'5',NaN,{}}
s.add({}); //Set{5,'5',NaN,{},{}}, Any two objects are not equal
  • Let's take a brief look at the other one and Set Similar data structure WeakSet

WeakSet Structure and Set similar , It's also a set of values that don't repeat . however , It is associated with Set There are two differences .

(1)WeakSet Members of can only be objects , It can't be any other type of value .

 var ws = new WeakSet();
// TypeError: Invalid value used in weak set
// TypeError: invalid value used in weak set

(2)WeakSet The objects in are all weak references , That is, garbage collection mechanism does not consider WeakSet Reference to the object , in other words , If no other object references that object , Then the garbage collection mechanism will automatically reclaim the memory occupied by the object , Regardless of whether the object still exists in WeakSet In . What does this feature mean , Can't quote WeakSet Members of , therefore WeakSet It's not ergodic .

3 New data structure Map

map The word itself has the meaning of mapping ,Map Data structure provides a perfect key value pair structure , The reason why we call it perfection is relative to the former , We know JS Objects in the Object Itself is a key value pair hash structure , However, this kind of key value pair is not perfect .

Object Only strings can be used as keys in , Cannot use object as key ,Map Data structure is proposed to solve this problem , Come and see a chestnut :

 var a = {};
var p = {name:'vicfeel'};
a[p] = 'val';
a;//Object {[object Object]: "val"},p Object is converted to a string “[Object Object]”

Take a look at Map Basic usage of data structure :

 // Constructors 
var m = new Map();
var p = {name:'vicfeel'};
// Add key value pair
// Get key value pairs
m.get(p); //"val"
m.get('name'); //undefined
// Return size
m.size; //1
// Adding the same key repeatedly will override the previous key
m.get(p); //"newVal" // Initialization with an array containing key value pairs Map, After the same key, the front will be covered
var arr = [{'name':'vicfeel'},{'age':23},{'age':25}];
var m2 = new Map(arr);
m2.get('age'); //25 // Determine whether there is a key
m2.has('name'); //true
// Delete a key
m2.has('name'); //false // Empty
m2.size; //0

in addition , in addition Map The data structure also has one forEach Method to traverse :

 let m = new Map();
console.log("Key: %s, Value: %s", key, value);
//Key: name, Value: vicfeel
//Key: age, Value: 25

4 Iterator( Iterator )

Although this blog is about new data types and data structures , The traverser is not in this column , take Iterator It's here because it's different from the one mentioned above Set、Map The connection is tight , Strike while the iron is hot , So I said it together .

Let's start with the traverser (Iterator) It's a mechanism 、 An interface , It provides a unified access mechanism for different data structures . Any data structure only needs to be deployed Iterator Interface (ES6 Regulations , default Iterator Interface deployed in data structure Symbol.iterator attribute ), You can complete the traversal operation ( That is, all members of the data structure are processed in turn ).

ES New traversal method for...of The traversal method is to find the object automatically Iterator Interface , Some data structures are deployed by default Iterator Interface , Including arrays 、Set and Map structure 、 Pseudo array ( such as arguments object 、DOM NodeList object )、 Later Generator object , And strings , So these data structures can be used directly for...of Traversal , Look at the chestnuts :

 let arr = [1,2,3];
for(let item of arr){
} let s = new Set(arr);
for(let item of s){
} let m = new Map();
let p = {'width':100,'height':200};
for(let item of m){
//["name", "vicfeel"]
//["age", 23]
} let str = 'hello';
for(let item of str){

For undeployed Iterator The structure of the interface you want to use for it for...of Traversal can be deployed on its own Iterator Interface , Example object Object The default is no deployment Iterator Interface , Because the system doesn't know which attribute to traverse from and in what order to traverse , Let's take an object and see how to deploy Iterator Interface :

 let obj = {
data: [ 'hello', 'world' ],
[Symbol.iterator]() {
const self = this;
let index = 0;
return {
//Iterator adopt next() Function to traverse , until next Function return done The value is true
next() {
if (index < {
return {
done: false
} else {
return { value: undefined, done: true };
}; for(let item of obj){

Reference resources Reference

Bowen author :vicfeel

The source of the blog :

The copyright of this article belongs to the author and blog Park , Welcome to reprint , But this statement must be retained , And give a link to the original , Thank You for Your Cooperation !

If you read this article , Feel helpful , You can click for my blog “ Recommend it ”!

towards ES6 par , Use better JavaScript( 3、 ... and ) More articles about

  1. Learn faster JavaScript Of 6 A thinking skill

    Learn faster JavaScript Of  6 A thinking skill We are learning JavaScript, Or any other coding skill , It's often because of these obstacles that I'm stuck : Some concepts may cause confusion , Especially when you're switching from another language ...

  2. Use Promises Write more elegant JavaScript Code

    You may have overheard that Promises, A lot of people are talking about it , Use it , But you don't know why they're so special . Can't you use callbacks ? There's something special ? In this paper , Let's see Promises What it is and how to use it ...

  3. [label][ translate ][JavaScript-Translation] Seven steps to write better JavaScript Code

    7 steps to better JavaScript Link to the original text : ...

  4. ( 6、 ... and ) my JavaScript series : better JavaScript And CoffeeScript

    A lot of genius in the world is working on building better JavaScript Efforts . There have been a lot of attempts , One of the most promising , does CoffeeScript and TypeScript 了 . face CoffeeScript, I feel as if I've met you at first sight ...

  5. Learn from the beginning JavaScript ( 3、 ... and )—— data type

    original text : Learn from the beginning JavaScript ( 3、 ... and )-- data type One . classification Basic data type :undefined.null.string.Boolean.number Complex data type :object object Of ...

  6. JavaScript The difference between the three ways of binding events

    JavaScript Three ways to bind events : 1. <div id="btn" onclick="clickone()"></div> // ...

  7. JavaScript Three ways to bind events

    JavaScript Three ways to bind events : 1. <div id="btn" onclick="clickone()"></div> // ...

  8. First time to know JavaScript( 3、 ... and )

    First time to know JavaScript( 3、 ... and ) Let me start with the last one < First time to know JavaScript( Two )> You know the type . value . Definition and characteristics of variable , In this section, I will learn JavaScript The arithmetic operations in . Binary floating point number and rounding error ...

  9. towards ES6 par , Use better JavaScript( One )

    as everyone knows ,JavaScript As a weak type language , It is always the coexistence of essence and dross. , many " Weird " We have to accept and use it . Actually ES6( also called ECMAScript 2015) stay 2015 year 6 The month is already in full swing ...

  10. towards ES6 par , Use better JavaScript( Two )

    This article is about ES6 The second part of the series , This paper mainly introduces ES6 The extension of existing object method attribute in , Go to the portal first : 1 Variable part 2 Existing objects expand 3 New data type / data structure 4 New asynchronous programming mode 5 Classes and modules 1 Added template string ...

Random recommendation

  1. Mongodb Installation

    download : mongodb-win32-x86_64-3.2.5-signed.msi   install : 1.dos Switch to the installation directory bin Next : 2 ...

  2. SDL The play

    extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> ...

  3. js What is enumerability in objects (enumerable)?

    When it comes to enumeration , Maybe a lot of people think of enumeration types , But in javascript Object has a property that is enumerable , What is he ? Concept Enumerability (enumerable) Used to control the properties described , Will it be included in the Cycle it ...

  4. MySQL Basic sentence and its application Python The use of

    One .MySQL Basic statement $ mysql -u root -p ( When there is a password ) $ mysql -u root     ( When there is no password ) QUIT (or \q)   sign out View all current databases show dat ...

  5. JAVA object-oriented ----- Access method of member inner class

    Access method of member inner class 1. The inner class can directly access the member properties of the outer class .( The monkey king is equivalent to the inner class flying into the belly of the ox demon king ). 2. When an external class needs to access the member properties of an internal class, it needs to create an object of the internal class . 1. Create an inner class in a member function of an outer class ...

  6. change redhat7 yum From centos

    1. Replace the original system yum package , Check the initial yum What's in the bag rpm -qa |grep yum 2. Delete the original yum package . rpm -qa|grep yum|xargs rpm -e --nodeps 3 ...

  7. angular.js Basic methods provided in

    angular.bind angular.callbacks angular.equals /* *Determines if two objects or two values are equiva ...

  8. IOS Preprocessing statement

    The source code in the program is not recognized by the computer , You need to translate the written code into 0.1 Binary code , Computers can recognize . There are two steps to turning source code into binary code , Compile and link . Compiling is to convert the code of each file into binary code through the compiler , In the process ...

  9. SpringBoot20 Integrate SpringSecurity02 -&gt; utilize SpringSecurity Separate the front end and back end for login verification

    1 SpirngBoot Environment building Create a SpringBoot The project is just , For details, please refer to sanshao's related blog Refer to the post -> Click to go to SpirngBoot Project scaffolding -> Click to go to 2 introduce Spirn ...

  10. Shader Learning notes

    Shader Learning notes Example : Shader "SrfShader1"{ // The definition is displayed in the Inspector The variables in the , And from Inspector Get the value Properties{ _Colo ...