es6 - use of variables, constants, deconstructions, objects, arrays

Posted by shamuraq on Wed, 22 Dec 2021 18:35:12 +0100

1, Variable

es5 uses var to declare a variable. The characteristics of var are different from those of conventional programming languages. Therefore, es6 provides a method of declaring variables similar to that of conventional languages.

let differs from var in that:

1. The variable declaration will not be promoted, that is, the variable cannot be used before the variable declaration

For example:

 console.log(a);

 let a=1;

The result will be an error and the let declaration cannot be promoted

2. It has local scope, that is, the variables declared by let can only be used in the corresponding code block

For example:

{

    let a=1;

}

console.log(a);

The block enclosed by a brace is a scope and is a local scope. Declared variables can only be used within this scope. Therefore, this piece will report an error that a is not defined.

3. Repeated declaration is not allowed.

For example:

let b = 1;

let b = {}

Repeated declaration of a variable will also make an error.

2, Constant

Variables in es6 are declared with let, and constants are declared with const. Const has the same features as let, and another feature is:

The variable declared by const needs to be assigned at the time of declaration, and can only be assigned once and cannot be modified.

For example:

const a=1;
a++;
console.log(a);

3, Deconstruction

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.

Common deconstruction of es6:

1. Array deconstruction (use square brackets):

(1) Complete deconstruction: if the patterns on both sides of the equal sign are the same, the variables on the left will be given corresponding values

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

The output result is: 1 2 3

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

The output result is: 1 [2,3] 4

(2) Incomplete deconstruction: the pattern on the left of the equal sign only matches part of the array on the right of the equal sign, and can be deconstructed successfully.

 let [a,b]= [1,2,3,4];
 console.log(a,b);

Output: 1 2

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

Output result: 1 2 4

(3) Collection deconstruction: using the... Extension operator, you can receive redundant data and return an array.

let [a,...b]=[1,2,3,4];
console.log(a,b);

Output result: 1 [2,3,4]

(4) when the default value is a number, (when the matching value is strictly equal to undefined, the default value takes effect)

let [a, b = 2] = [1, 3];
console.log(a, b);

Output results: 1 3

When let [a,b=2]=[1]

console.log(a,b);

The output result is 1.2 / / because a on the left will match 1 on the right, and b has no matching content, it will return undefined. At this time, the default value takes effect, so b=2

(5) The default value is function

function myFun(){
    console.log('123');
}
let [a=myFun()]=[];
console.log(a);

The output result is undefined / / because the myFun function here does not return a value

The default value is the function, and the function has a return value

function myFun(){
    console.log('123');
    return 10;
}
let [a=myFun()]=[];
console.log(a);

2. Object deconstruction: put the variables on the left of the equal sign inside the 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 in order to get the correct value.

When the variable name is consistent with the attribute name,

It can be written as: let {foo, bar} = {foo: "AAA", bar: "BBB"}// foo = "aaa”; bar = "bbb”

It can be abbreviated as: let {foo, bar} = {foo: "AAA", bar: "BBB"}// foo = "aaa”; bar = "bbb”

When the variable name and attribute name are inconsistent,

Must be written as: VAR {foo: Baz} = {foo: 'AAA', bar: 'BBB'}// baz = "aaa”

Nested deconstruction:

let obj={p:['hello',{y:'world'}]};
let{p:[a,{y:b}]}=obj;
console.log(a+b);

The output result is helloworld

3. String deconstruction: if the variable to the left of the equal sign is placed in square brackets, it is similar to array deconstruction, and the specified character is obtained from the string; If it is similar to object deconstruction in braces, it is deconstructed from the instance property method.

The variable to the left of the equal sign is placed in square brackets (similar to array deconstruction)

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

Variables to the left of the equal sign are placed in braces (similar to object deconstruction)

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

4, Object

1. Object abbreviation: ES6 specifies that variables and functions can be written directly into the object as the object's attributes and methods. At this time, the attribute name is the variable name and the attribute value is the value of the variable.

For example:

let username='Zhang San';
let obj={
    username,//Is short for username:username
    sayName:function(){
        // ES5 methods for declaring functions in objects
    },
    sayAge(){
         // ES6 methods for declaring functions in objects
    }
}

 2. Object

(1) Object.is(value1,value2): compares whether two values are the same. This method does not cast types.

"= =" indicates that type conversion will be performed before comparison

"= = =" means to compare types first. As long as the types are different, they must be different

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

(2) Object.assign(): deep cloning, cloning with one parameter and splicing with two parameters

let obj={
    name:'Zhang San'
}
let obj1={
    name:'Li Si',
    age:12
}
let newObj={};
// clone
Object.assign(newObj,obj);//Clone the contents of obj into the empty object newObj
// Splicing
Object.assign(newObj,obj,obj1);//Here, the contents of obj and obj1 are spliced and cloned into newObj. The output is name: Li Si, age:12. For the same attributes, the later ones will overwrite the previous ones

(3) Object.setPrototypeOf(obj,prototype): sets the prototype object of the object. If the second parameter is not an object or null, the function does nothing.

 

 let obj1 = {
    name: 'zhangsan',
    age: 12
  }
  let obj2 = {
    name: 'lisi',
    gender: 'male'
  }
  // Set the prototype of obj1
  Object.setPrototypeOf(obj1, obj2);
  // Get the prototype of obj1
  console.log(obj1.__proto__);
  console.log(obj1.constructor.prototype);
  console.log(Object.getPrototypeOf(obj1));

(4) Object.keys(obj) returns the array of all enumerable attributes of the object itself, excluding the prototype chain.

That is, an array of all attributes is returned.

Object.values(obj) gets the values of all attributes of the object and returns the array of enumerable attribute values of the object itself, that is, an array composed of all attribute values

Object. The entries () method returns an array of key value pairs of enumerable properties of a given object. Its arrangement and use for When the in loop traverses the object, it returns in the same order (the difference is that the for in loop also enumerates the attributes in the prototype chain).

let obj1 = {
    1: 'Zhang San',
    2: 'Li Si',
    3: 'Wang Wu'
  }
  
  let key = Object.keys(obj1);
  let value = Object.values(obj1);
  let entry = Object.entries(obj1);
  console.log(key);
  console.log(value);
  console.log(entry);

5, Array

  1. Extender: use three points'... ' express. It is like the inverse operation of rest parameters, turning an array into a comma separated sequence of parameters.

(1) use the expansion operator to merge the arrays

let arr1=[1,2,3];
let arr2=[4,5,6];
let arr=[...arr1,...arr2];
console.log(arr);

(2) the extension operator, placed to the right of the equal sign, is used to expand (peel)

let obj1={
    name:'zhangsan',
    age:12
}
let obj2={
    ...obj1,
    gender:male,
    hobby:'Basketball',
}
console.log(obj2);

(3) convert string to array

let newArr=[...'hello'];
console.log(newArr);

 2. Static method of array (Array.of())

let arr=new Array(3);//Indicates that the length of the arr array is 3. This method indicates the length when there is only one parameter.

console.log(arr);//Three empty items will be output

let arr3 = new Array('3');//Indicates that there is only one content, and it is 3
console.log(arr3);

let arr1=Array.of(3);//The element passed is 3
let arr2=Array.of(3,3,3,3);//What is passed is the content of each item
console.log(arr1);
console.log(arr2);

 

 3. Array instance method

(1) The find method returns the first element that satisfies the condition

let arr1=['Li Si','Wang Wu','Old six','Zhang San'];
//The find method returns the first element that satisfies the condition
let result = arr1.find(item => {
  return item === 'Zhang San'
})
console.log(result);

(2) findIndex() returns the index of the first element that satisfies the condition

let result = arr1.findIndex(item => {
  return item === 'Zhang San'
})
console.log(result);

(3) The includes() method is used to determine whether the string contains the specified substring.

let result = arr1.includes('Zhang San');
console.log(result);//true

(4) fill() fills the array and fills all elements in the array with arguments

arr1.fill(1)
console.log(arr1);

(5) Use of keys(), values(), and entries() methods

let arr1 = ['Zhang San', 'Li Si', 'Wang Wu', 'Old six'];
let key = arr1.keys();
let value = arr1.values();
let entry = arr1.entries();
console.log(key); 
console.log(value);
console.log(entry);
Returns the iterator object of the array, which can be used through.next()Accessing internal values:{ value: 0, done: false }
console.log(key.next());
console.log(key.next());
console.log(key.next());
console.log(key.next());
console.log(key.next());

When done is false, it means there are elements behind it, and when it is true, it means there is no subsequent value. There are four elements in the array here, when there is a fifth If you access next(), it will be displayed as {value: undefined, done: true}

 

Topics: Javascript