ES6 variable, deconstruction, object, array, function learning

variable

Variables are declared with let in ES6. Let has the following characteristics:
1. The variable declaration will not be promoted, that is, the variable cannot be used before the variable declaration

console.log(name);//ReferenceError:Cannot access 'name' before initialization
let name='zhangsan';
// console.log(name);//zhangsan
  1. With local scope, that is, variables declared by let can only be used in the corresponding code block
let name='zhangsan';
{
    let name1='lisi'
    console.log('inside:',name1,name);//Internal: lisi zhangsan
}
console.log('external:',name);//External: zhangsan
for (var i = 1; i < 10; i++) {
   console.log(i);  
}
console.log('for Cycle external',i);
//If you want the external to get the internal, use var; If you don't want to get the inside, use let


3. Repeated declaration is not allowed.

const b=1;
const b=true;
//SyntaxError: Identifier 'b' has already been declared

constant

const declares constants with the same characteristics as let. In addition:
4.const declared variables need to be assigned at the time of declaration, and can only be assigned once and cannot be modified

const c;//SyntaxError: Missing initializer in const declaration
const c=0;//No change is allowed after this statement
c++ //Reassignment of typeerror is not allowed: assignment to constant variable

deconstruction

ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstruction. The essence of deconstruction belongs to "pattern matching". As long as the patterns on both sides of the equal sign are the same, the variables on the left will be given corresponding values. If the deconstruction is unsuccessful, the value of the variable is equal to undefined.

Array deconstruction

The variable to the left of the equal sign is placed inside the square brackets to match the elements in the array on the right

Incomplete deconstruction

let[a,b,c]=[1,[2,3],4]
console.log(a,b,c);//1 [ 2, 3 ] 4
//Deconstruct b ↓
let[a,[b],c]=[1,[2,3],4]
console.log(a,b,c);//1 2 4 deconstruct b

// Incomplete deconstruction of arrays
let [a,b]=[1,2,3]
console.log(a,b);//1 2

Set deconstruction

Extension operator... Used on the left of = to aggregate and generate new objects or arrays; It is used on the right of = and has the function of splitting / stripping

let [a,...b]=[1,2,3]
console.log(a,b);//1 [2, 3] the remaining unmatched elements are repackaged into an array

Default deconstruction

let[a,b,c=10]=[1,2,3]//c the default value of 10 is used when the value is not available
console.log(a,b,c);//123

//Set the default value for array deconstruction (the default value can also be a function)
function myFun(){
    console.log('function');
    return 100;
}
let [a,b,c=myFun()]=[1,2]
console.log(a,b,c);//1 2 100

Object deconstruction

The variables to the left of the equal sign are placed inside braces to match the elements in the array on the right. The attributes of the object have no order. The variable must have the same name as the attribute to get the correct value

let {name:uesrname,age:userage}={name:'Zhang San',age:12}
console.log(uesrname,userage);//Zhang san12
//Short form of object (omit the key value and keep the value corresponding to value)
let {name,age}={name:'Zhang San',age:12}
console.log(name,age);//Zhang san12

If the variable name and attribute name are inconsistent, you need to rename them

let {foo:baz}={foo:"hello",bar:"world"};
console.log(baz);//hello

Nested deconstruction

let obj={p:['Hello',{y:'World'}]};
let {p:[a,{y:b}]}=obj;
console.log(a+b);//HelloWorld

Default deconstruction

let{name,age,gender='male'}={name:'Zhang San',age:12,gender:'female'}
console.log(name,age,gender);//Zhang San 12 female

Interview questions

const [a, b, c, ...d] = [1, 2, 3, 11, 999];
const { e, f,f1, g, ...h } = { f: 4, g: 5, i: 6, j: 7 };
console.log(a, b, c, d, e, f1, g, h);
//1 2 3 [ 11, 999 ] undefined undefined 5 { i: 6, j: 7 }

String deconstruction

You can use the array structure [] to get the specified character

let [a,b,c,d,e]='hello'
console.log(a,b,c,d,e);//h e l l o

Use the object structure {} to get the instance property method

let{ length,toString}='hello'
console.log(length,toString);//5 [Function: toString]

String to array (array deconstruction extension operator)

let [...arr]='hello'
console.log(arr);//[ 'h', 'e', 'l', 'l', 'o' ]

Numerical deconstruction

Gets the method specified in the numeric wrapper constructor prototype

let{toString,valueOf}=10
console.log(toString,valueOf);//[Function: toString] [Function: valueOf]

Boolean deconstruction

Gets the method specified in the Boolean wrapper constructor prototype

let{valueOf}=true
console.log(valueOf);//[Function: valueOf]

object

Object abbreviation

let name='Zhang San'
let age=12
let obj={
    sayName() {
        console.log(this.name);
    },
    age
    // Equivalent to age:age in es5
}
obj.sayName()//Call the sayName function

Object Api extension

The extension of Object in ES6 is mainly the extension of static methods
Object.is(a,b) compares whether the two values are the same

console.log(1===1);//true
console.log(Object.is(1,1));//true

console.log(+0===-0);//true
console.log(Object.is(+0,-0));//false

console.log(NaN===NaN);//false
console.log(Object.is(NaN,NaN));//true

The two parameters Object.assign() are used to copy and copy objects. The first parameter is the target object

let obj1={}
let obj2={
    name:"zhangsan",
    age:12
}
let obj3={
    name:'lisi',
    gender:'male'
}
// Object.assign(obj1,obj2); // {Name: 'Zhangsan', age: 12} copy the contents of obj2 into obj1 object and return obj1 object
Object.assign(obj1,obj2,obj3); //{name: 'lisi', age: 12, gender: 'male'} if the attribute in the target object has the same key, the attribute will be overwritten by the attribute in the source object
//The three parameters represent the merging objects obj2 and obb3 into obj1 and return the obj1 object
console.log(obj1);
// console.log(obj1===obj2);//false implements a shallow copy

Object.getPrototypeOf() gets the method in the prototype object
Object.setPrototypeOf() sets the method in the prototype object

let obj1={}
let obj2={
    name:"zhangsan",
    age:12
}
let obj3={
    name:'lisi',
    gender:'male'
}
Object.setPrototypeOf(obj1,obj2)
console.log(Object.getPrototypeOf(obj1));//[Object: null prototype] {}

Object.keys() gets an array of all attribute names

let obj={
    name:'zhangsan',
    age:12,
    gender:'male'
}
let keys =Object.keys(obj)
console.log(keys);//[ 'name', 'age', 'gender' ]

Object.values() gets an array of all attribute values

let values=Object.values(obj)
console.log(values); 
//[ 'zhangsan', 12, 'male' ] 

Object.entries() gets an array of key value pairs

let entries=Object.entries(obj)
console.log(entries);
//[ [ 'name', 'zhangsan' ], [ 'age', 12 ], [ 'gender', 'male' ] ]

function

ES6 allows you to set default values for function parameters, that is, write them directly after the parameter definition. Generally, the parameter with default value defined should be the tail parameter of the function. The length property of the function will return the number of parameters without default value specified

    function log(x, y = 'World',d) { 
        console.log(x, y);
    }
    // log(1,2)
    console.log(log.length)

Function parameter deconstruction

Function parameter object deconstruction

let myFun1=function(a,b,c){
    console.log(a,b,c);//null 2 undefined
}
myFun1(null,2);

Function parameter object default value deconstruction

let myFun2=function ({a,b,c=100}) {
    console.log(a,b,c);
}
myFun2({a:1,c:2,b:'tom'})//1 tom 2
// myFun2({a:1,b:'tom'})//1 tom 100

Deconstruction of function parameter array

let myFun3=function([a,b,c]){
    console.log(a,b,c);//1 2 3
}
myFun3([1,2,3])

ES6 introduces the rest parameter (in the form of... Variable name) to obtain the redundant parameters of the function, so there is no need to use the arguments object

// ... used in the position of function parameters, it is called rest function, also known as the inverse operation of extension operator
let myFun4=function (a,...b) {
    console.log(a,b);
}
myFun4(1,2,3,4,5,6)//1 [ 2, 3, 4, 5, 6 ]

Arrow function

The arrow function does not have its own this, but refers to the outer this

let arr=['tom','lerry','jacky']
let result2=arr.filter((item)=>{
    return item=='tom'
})
console.log(result2);//[ 'tom' ]

The arrow function is a minimalist form with only one return statement

let result=arr.filter(item=>item=='tom')
console.log(result);//[ 'tom' ]

this

let  obj = {
    name:'zhangsan',
    age:12,
    gender:'male',
    sayName:()=>{
    // Point to global scope
        console.log(this);//{}
    }
}
obj.sayName();
let  obj = {
    name:'zhangsan',
    age:12,
    gender:'male',
    sayName(){
        return()=>{
            // Points to the scope of the sayName function
            console.log(this);
        }
    }
}
obj.sayName()();//{name: 'zhangsan',age: 12,gender: 'male',sayName: [Function: sayName]}

array

Extension operator

let obj1={
    name:'zhangsan',
    age:12,
    gender:'male'
}
let obj2={
    ...obj1,
    gender:'male'//When the property values conflict, the following overrides the previous 
}
console.log(obj2);//Peel obj 1 and put it into obj 2

Array API extension

Array.from()

let obj={
    0:'Zhang San',
    1:'Li Si',
    2:"Wang Wu",
    length:3
}
let arr=Array.from(obj)
console.log(arr);//['Zhang San', 'Li Si', 'Wang Wu']

Array.of()

let arr1=Array.of(3,"tom")
console.log(arr1);//[ 3, 'tom' ]

Array.prototype.find()

// The find method returns the first element that satisfies the condition
let arr1=Array.of(1,2,3,4,5)
let result=arr1.find((item,index)=>{
    return item>2
})
console.log(result);//3

Array.prototype.includes()

// includes determines whether there are currently passed elements in the array
let arr1=Array.of(1,2,3,4,5)
let result=arr1.includes(1)
console.log(result);//true

Array.prototype.fill()

// Fills all elements in the current array as passed elements
let arr1=Array.of(1,2,3,4,5)
let result=arr1.fill(7)
console.log(result);//[ 7, 7, 7, 7, 7 ]
console.log(result===arr1);//true(fill changes the original array)

Array.prototype.keys() | Array.prototype.values() | Array.prototype.entries()

let arr1=Array.of(1,2,3,4,5)
let keys =arr1.keys()
let values=arr1.values()
let entries=arr1.entries()
console.log(keys,values,entries);
//Object [Array Iterator] {} Object [Array Iterator] {} Object [Array Iterator] {}

Set

initialization

let arr =[1,2,3,4,4,5,3,2,1,7]
let set = new Set(arr)
console.log(set);//Set(6) { 1, 2, 3, 4, 5, 7 }

Set API

Set.prototype.size

let arr =[1,2,3,4,5]
let set = new Set(arr)
console.log(set.size);//5 returns the total number of set instances

Set.prototype.add(value)

let arr =[1,2,3,4,5]
let set = new Set(arr)
set.add(100)
console.log(set);//Set(6) { 1, 2, 3, 4, 5, 100 }

Set.prototype.delete(value)

let arr =[1,2,3,4,5]
let set = new Set(arr)
// When a value is deleted, a Boolean value is returned to indicate whether the deletion is successful
set.delete(1);//true
console.log(set);//Set(4) { 2, 3, 4, 5 }

Set.prototype.has(value)

let arr =[1,2,3,4,5]
let set = new Set(arr)
// Returns a Boolean value indicating whether the value is a member of Set
console.log(set.has(1));//true

Set.prototype.clear()

let arr =[1,2,3,4,5]
let set = new Set(arr);
// //Clear all members, no return value
set.clear();
console.log(set);//Set(0) {}

Set.prototype.keys()

Iterator that returns the key name

Set.prototype.values()

Iterators that return key values

Set.prototype.entries()

Returns the traversal of key value pairs

Map

initialization

let map=new Map();
console.log(map);//Map(0) {}

Map API

Set.prototype.set(key, value)

let obj1={
    name:'zhangsan',
    age:12,
    gender:'male'
}
let map=new Map(Object.entries(obj1));
map.set(true,0);
map.set({a:1,b:2},['tom','ricky'])
console.log(map);

Set.prototype.forEach()

let obj1={
    name:'zhangsan',
    age:12,
    gender:'male'
}
let map=new Map(Object.entries(obj1));
map.forEach((value,key)=>{
    console.log(value,key);
})

iterator

Iterator has three functions: one is to provide a unified and simple access interface for various data structures; Second, the members of the 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 for... Of consumption.

let arr1=['tom','vicky','jacky']
let keys=arr1.keys()
let values=arr1.values()
let entries=arr1.entries()
for(let entry of entries){
   console.log(entry);// [ 0, 'tom' ] [ 1, 'vicky' ] [ 2, 'jacky' ]
}
for(let value of values){
-    console.log(value);//tom vicky jacky
}

Reconstruction of for of loop

let arr1=['tom','vicky','jacky']
let values=arr1.values()
let item;
while ( !(item= values.next()).done) {
    console.log(item.value);//tom vicky jacky
}

Tags: Javascript node.js

Posted on Mon, 27 Sep 2021 09:50:19 -0400 by ashly