From (Introduction to ES6 standard) (3rd Edition) (by Ruan Yifeng) classic case - in continuous update
1. An example of simulating the return value of next method
function makeIterator(array){ var nextIndex = 0; return { next: function(){ return nextIndex < array.length ? {value: array[nextIndex++],done:false} : {value: undefined, done: true}; } } } var it = makeIterator(['a','b']); it.next(); // {value: "a", done: false} it.next(); // {value: "b", done: true} it.next(); // {value: undefined, done: true}
2. Implement AJAX operation with Promise object
// Create getJSON method var getJSON = function (url) { var promise = new Promise(function(resolve,reject){ var client = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP'); client.open('GET',url); client.onreadystatechange = handler; client.responseType = 'json'; client.setRequestHeader('Accept','application/json'); client.send(); function handler() { if(this.readyState===4) { if(this.status ===200) { resolve(this.response); }else { reject(new Error(this.statusText)); } } } }) return promise; } // Call method getJSON('https://www.qinghuo.ltd:8888').then(function(json){ console.log('Background return data'+json); },function(err){ console.log('Access error'+err); })
3. Purpose of deconstruction and assignment of variables
-
Value of exchange variable
let x = 1; let y = 2; [x,y] = [y,x]; //The above code exchanges the values of variables x and y, which is not only concise, but also easy to read and has very clear semantics
-
Return multiple values from function
// Returns an array function example() { return [1,2,3]; } let [a,b,c] = example(); // Return an object function example() { return { foo: 1, bar: 2 } } let {foo,bar} = example();
-
Definition of function parameters
// The deconstruction assignment can easily correspond a group of parameters with variable names // Parameters are a set of ordered values function f([x,y,z]) {...} f([1,2,3]); // Parameter is a set of unordered values function f({x,y,z}) {...} f({z:3,y:2,x:1});
-
Extract JSON data
// Deconstructing assignments is particularly useful for extracting data from JSON objects let jsonData = { id: 42, status: "OK", data: [876, 534] }; let {id,status,data:number} = jsonData; console.log(id,status,number); // 42,"OK",[876, 534]
-
Default value of function parameter
JQuery.ajax = function (url, { async = true, beforeSend = function () {}, catch = true, complete = function () {}, crossDomain = false, global = true, // ... more config }) { // ... do stuff }; // Specify the default value of the parameter, so as to avoid writing var foo = config.foo | 'default foo' statements inside the function body
-
Traversal Map structure
// Any object deployed with iterator interface can use for...of loop traversal. Map structure supports iterator interface natively. It is very convenient to obtain key name and value with variable deconstruction and assignment var map = new Map(); map.set('first','hello'); map.set('second','world'); for(let [key,value] of map) { console.log(key + 'is' + value); } // first is hello // second is world // If you only want to get the key name or the key value, you can write as follows // Get key name for(let [key] of map) {...} // Get key value for(let [,value] of map) {...}
-
Input module specifying method
// When loading a module, it is often necessary to specify the input method. Deconstruction and assignment make the input statement very clear const {SourceMapConsumer, SourceNode} = require("source-map");
4. Four methods to determine whether a string is contained in another string
-
indexOf(): returns Number, indicating the index of the value in the string. If it is not found, it returns - 1
-
includes(): returns a Boolean value indicating whether the parameter string is found
-
startsWith(): returns a Boolean value indicating whether the parameter string is in the header of the source string
-
endsWith(): returns a Boolean value indicating whether the parameter string is at the end of the source string
// Case: var s = 'hello world!'; console.log(s.indexOf('e')) // 1 console.log(s.includes('e')) // true console.log(s.startsWith('h')) // true console.log(s.endsWith('!')) // true
5. Tail recursion
Recursion consumes a lot of memory, because hundreds of call frames need to be saved at the same time, so it is easy to have a "stack overflow" error. However, for the last return, because there is only one call frame, there will never be a "stack overflow" error
// Normal recursive call, factorial function factorial(n) { if(n===1) { return 1; }else { return n*factorial(n-1); } } factorial(5) // 120 // Tail Recursive Call function factorial(n,total) { if(n===1) { return total; }else { return factorial(n-1,n*total); } } factorial(5,1) // 120 //The above code is a factorial function. To calculate the factorial of N, you need to save at most N call records with a complexity of O(n). If you change it to tail recursion and keep a call record with a value, the complexity is O(1) //Normal Fibonacci series function Fibonacci (n) { if(n<=2) { return 1; }else { return Fibonacci (n-1) + Fibonacci (n-2); } } Fibonacci (10) // 89 Fibonacci (100) // stack overflow Fibonacci (500) // stack overflow // Fibonacci sequence of tail recursive optimization function Fibonacci2 (n, ac1 = 0, ac2 = 1) { if(n<=1) { return ac2; }else { return Fibonacci2 (n-1, ac2, ac1+ ac2) } } Fibonacci2 (100) // 5731478440138430000 Fibonacci2 (1000) // 7.022033e+208 Fibonacci2 (10000) // Infinity
6. Traversal of attributes
-
for in
for...in loops through the object itself and inherited enumerable properties (excluding Symbol properties)
-
Object.keys(obj)
Object.keys returns an array, including all enumerable properties (excluding Symbol properties) of the object itself (excluding inherited properties)
-
Object.getOwnPropertyNames(obj)
Object.getOwnPropertyNames returns an array containing all the properties of the object itself (excluding Symbol properties, but including non enumeration properties)
-
Object.getOwnPropertySymbols(obj)
Object.getOwnPropertySymbols returns an array containing all Symbol properties of the object itself
-
Reflect.ownKeys(obj)
Reflect.ownKeys returns an array containing all the properties of the object itself, whether the property name is Symbol or string, and whether it is enumerable or not
The above five methods follow the same rules of attribute traversal order when traversing object attributes
- First, all the attributes named numerical value are traversed and sorted by number
- Next, all the attributes named string are traversed and sorted according to the generation time
- Finally, all attributes named Symbol value are traversed and sorted according to the generation time
For example: Reflect.ownKeys({[Symbol()]:0,b:0,10:0,2:0,a:0}) // ['2','10','b','a',Symbol()]
7. The role of iterator
Iterator has three functions: one is to provide a unified and simple access interface for various data structures; Second, the members of data structure can be arranged in a certain order; Third, ES6 creates a new traversal command -- for of loop, and the Iterator interface is mainly used for of consumption
8.Iterator traversal
1. Create a pointer object that points to the starting position of the current data structure. That is to say, the traverser object is essentially a pointer object 2. The next method of the pointer object is called for the first time, which can point the pointer to the first member of the data structure 3. Call the next method of the pointer object for the second time, and the pointer points to the second member of the data structure 4. Call the next method of the pointer object until it points to the end of the data structure
9. Five methods of asynchronous programming
- Callback function
- event listeners
- Publish / subscribe
- Promise object
- Generator function