Practice the new features of js 6 es6

1. Deconstruction and assignment

es6 allows us to extract values ​​from arrays or objects and assign them to other variables according to a certain pattern. This is called structural assignment. Let us look at a simple example.

var [a,b,c] = [1,2,3];
console.log(a); // 1

This code assigns the values ​​of the array on the right to the three variables a, b, and c. This is just the simplest application, it can be more complicated, for example

var [a,[b],c] = [1,[2,3],4];
// 这也可以

Since arrays can be copied structurally, then as for objects, the answer is yes, and objects are also possible. E.g

var {
    
    a, b} = {
    
    a:10,b:20 }

It is worth noting that the variable name in the front and the property name in the back must be consistent, so that they can be accessed. If they are inconsistent, the value is undefined. When you see this, you suddenly feel that the deconstruction and assignment of the object is pretty closed. Don't continue to look down. What do we do if we want to change the name of a variable for him? Please see

var {
    
    a:name , b:age} = {
    
    a:10,b:20};

ok! Now we can name,ageaccess it through, of course, this is only the simplest application of object structure assignment.

2. Generitor (generator)

This is a new addition to es6, so what is it? It is a new function introduced by the ES6 standard. Its definition does not look much different from the function. Let us first see how it looks different from ordinary functions

// 函数
function demo(){
    
    
	return "ok fine my name is function";
}

// generitor对象
function* gen(){
    
    
	 yield "ok this is generitor";
	 let name = yield "name is gen";
	 return name;
}

ok doesn’t seem to make a big difference, but it’s just a new keyword added to the function body using function* definition. Is this really the case? So what does this keyword do? When the execution of this function encounters yield, it will return the value behind it, but this function has not been executed in a real sense. It just gives control to other functions to execute. When the next() method is executed, it returns to the previous value. Where the execution is aborted, the next() function can pass parameters, the first next() is invalid, and the first next() is more like an initiator. E.g

let _increment = function* increment(){
    
    //
    let i = 1;
    while(i){
    
    
        yield i++;
    }
}
var _increment = increment()
console.log(_increment.next());
console.log(_increment.next());
// 无限自增函数

Want to learn more about generitor click here or here

Guess you like

Origin blog.csdn.net/weixin_43889562/article/details/108126423