Front end - Advanced JavaScript

JS advanced

JS AD Day 01

Object oriented programming OOP: encapsulation, inheritance, polymorphism

Use functions to divide problems, not steps.

Classes and objects

In js, an object is an unordered collection of related attributes and methods, and everything is an object. For example, strings, functions, arrays, etc.

Objects are composed of properties and methods.
Attributes are the characteristics of things.
Method is the behavior of things.

Extract the common attributes and behaviors of objects and organize them into a class. That is, the common attributes and behaviors of abstract objects are encapsulated into a template.
Instantiate the class and get the object of the class.

Class, class, class abstracts the common part of an object and generally refers to a large class.
Object refers specifically to a class, which instantiates a specific object through a class.

1. Create class

Syntax: initial capitalization

class MyClassName {
//class body 

Create instance:

var xxx = new MyClassName();

Class must use new to instantiate the object.

Constructor constructor

The constructor() method is the constructor of the class (the default method). It is used to pass parameters and return the instance object. When the instance object is generated through the new command, this method will be called automatically. If it is not written, it will be generated automatically.


class Star {
    constructor(uname,age) {
        this.uname = uname;
        this.age = age;
  //Note that the context separation functions here are not added,
  //And write functions without adding function
    say() {

var ldh = new Star('Lau Andy',18);


1) Class keyword to create a class, and the class name is capitalized
2) Class has a constructor function, which can receive the passed parameters and return the instance object at the same time
3) When using the new keyword, the constructor will be called automatically and will be generated automatically without writing.
4) When creating a class, you cannot add () after the class name to generate an instance, and you can add parentheses after the class name.
5) The constructor does not need to add function, all functions in the class do not need to add function keyword, and multiple function methods do not need to be separated by ','.

Inherit extensions

Extensions, subclasses can inherit some properties and methods of the parent class.

 class Father {
            money() {

class Son extends Father {

var son = new Son();;

super keyword

Used to access and call functions on the parent class. You can call the constructor of the parent class or ordinary functions.

class Father {
constructor(x,y) {
    this.x = x;
    this.y = y;
    sum() {
        console.log(this.x + this.y);

class Son extends Father {
	constructor(x,y) {
        super (x,y)//The constructor in the parent class was called
    //A normal function in the parent class was called
    console.log(super.say()+'My son')
    var son = new Son(1,2);

super keyword can call the parent constructor or ordinary function.
extends inherits the principle of proximity. When there is a conflict between a father and a son, the one who is close to him shall be executed first.
If you want to output the methods in the parent class, adding super.say(), super.say() is to call the ordinary function say() in the parent class;
super is used in subclass construction and must be called before the this of the subclass.

Class and object

1. In ES6, the class has no variable promotion, so you must define the class before you can instantiate the object through the class.
2. The common attributes and methods in the class must be used with this.
3. this in the constructor refers to the created instance object. The method in the class points to the caller, who calls to whom. Like a btn

//You can call the method directly in constructor, so as long as new, it will be directly executed.
   class MyName{
            this.x = x
            this.y = y
            this.say()//Pay attention to add this

        say() {
            console.log('sing a song')
    new MyName

TAB column switching case

Take the whole tab column form as an object, first abstract out the class, and then new one. Various methods, such as create, switch, delete, etc., are written in the class and then registered in the init method.


insertAdjacentHTML(positon,text); Parse the specified text into HTML or XML, and insert the result node into the specified location.

A DOMString that represents the position of the inserted content relative to the element, and must be one of the following strings:

  • 'before begin': before the element itself.
  • 'after begin': before inserting the first child node inside the element.
  • 'before end': after inserting the last child node inside the element.
  • 'after end': after the element itself.

appendChild does not support strings, insertAdjacentHTML does.

Double click event: ondbclick

The default action of double clicking is to select the text, so use the following code to clear the default action:


The core idea is that when you double-click the text, a text box is generated in it. When you go to the focus or press enter, you can give the value entered in the text box to the original element.

JS AD 02

Constructors and prototypes

Before ES6, there was no concept of class and inheritance.
The implementation of these functions is based on building functions and prototypes.

Before ES6, objects were not created based on classes. They were defined by a special function called constructor.

Create object example:

// 1. Create an object with new Object()
var obj1 = new Object();
	var obj = new Object();
	obj.uname = 'nancy'; = female;
	obj.sayHi = function() {
// 2. Create objects using object literals
        var obj2 = {};
		var obj2 = {
		username: "charlotte",
		sayHi: function() {
// 3. Create objects using constructors
        function Star(uname, age) {
            this.uname = uname;
            this.age = age;
            this.sing = function() {
                console.log('I can sing');
        var ldh = new Star('Lau Andy', 18);
        var zxy = new Star('Xue You Zhang', 19);

class method example:

class Star {
    constructor(uname,age) {
        this.uname = uname;
        this.age = age;
    say() {

var ldh = new Star('Lau Andy',18);

js is a dynamic language

Precautions for constructor method:
1. Instance members are members specified by this inside the constructor, such as name, age, etc.
Instance members need to be accessed through the instantiated object. The instantiated object refers to var ldh = new Star('andy Lau ', 18); ldh in.
2. Static members. For members added to the constructor itself, sex is a static member. Static members - members added directly to the constructor are called static members = 'male';
Static members can only be accessed through constructors, not objects. An error will be reported through console.log(

  function Hero(name, blood, weapon) {
      // Instance member / object member -- the member related to the object, which will be called in the way of the object in the future = name;
      this.blood = blood;
      this.weapon = weapon;
      this.attack = function () {
        console.log(this.weapon + ' Attack the enemy');

    // Static member -- a member added directly to the constructor
	// Warning here is given to the constructor itself
    Hero.version = '1.0';
    var hero = new Hero('Liu Bei', 100, 'The sword');

    var hero1 = new Hero('Guan Yu', 100, 'knife');
    // Static members cannot be called in the way of objects
    console.log(hero.version); Pay attention here h Is lowercase

    // Static members use constructors to call
    console.log(Hero.version); //Note that H is capitalized here

Constructor problem: memory waste. Simple data types are copied directly, and multiple complex data types with the same function need to open up new memory space for storage. Comparing two functions is the address of the comparison.


The function allocated by the constructor through the prototype is shared by all objects. js specifies that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be owned by the constructor.


Immutable methods can be defined directly on prototype objects, and all objects can share these methods.

A prototype is an object that shares methods. Public properties are defined in constructors and public methods are defined in prototypes.

Object prototype__ proto__

Objects have a property__ proto__ , The prototype object that points to the constructor.
In short, objects pass through__ proto__ Property, pointing to the prototype object. The two are equivalent.

Print object prototype console.log(obj1)
Check whether it is equivalent to console.log (oobj1. _ proto = = = star. Prototype)

constructor property

Object prototype (_proto_) and constructor prototype object (prototype) have a property: constructor property. Constructor we call it a constructor, which refers back to the constructor itself.

Constructor is mainly used to record which constructor the object refers to. Star.prototype.constructor will also point to star.

When there are many objects stored in prototype, they can be stored in the form of objects. However, this form will overwrite all the original contents of the prototype, resulting in the loss of the original default attribute methods and the invalidation of the constructor.
At this point, you can manually redirect to the constructor.

    function Star(uname,uage) {
   = uname;
            this.age = uage;

        Star.version = 1.0
//Object to store more methods
        Star.prototype = {
          //Manually refer back to the original constructor
                console.log('i can sing')
                console.log('i can perform movie')

        var ldh = new Star('ldh',18)

    console.log(ldh.__proto__ === Star.prototype)

Relationship between constructor instances and prototypes

Prototype chain

JS member lookup mechanism

Search according to the prototype chain and push up one level until null.

Static and dynamic types

Statically typed language:
It refers to a language in which the data type of a variable can be determined at compile time. Most statically typed languages require that the data type must be declared before using a variable. Some modern languages with type derivation ability may partially alleviate this requirement.

Dynamically typed language:
Is the language that determines the data type at run time. A variable does not need a type declaration before it is used. Usually, the type of the variable is the type of the value assigned. For example, in python, if the variable a=1, the type of a is an integer. If a = "abc", the type of a is a string.

Constructor this points to

Who calls to whom

In the constructor, this points to an object instance. This of the method in the prototype object points to the instance object.

Extend built-in objects

You can extend and customize the original built-in object through the prototype object.
For example, add an even sum operation to an array object.

Note: array and string built-in objects cannot be overwritten by prototype objects. Prototype = {}, can only be = function() {}.


Inheritance before ES6

There was no extensions inheritance before ES6. You can simulate inheritance through constructor + prototype object, which is called composite inheritance.


Call the previous function and modify the this point when the function runs,arg1,arg2...)

thisArg: currently calling the pointing object of function this.
arg1, arg2 other parameters passed

Borrowing constructor to inherit parent type property method

Inherit parent type properties

   function Father(faname,faage){ = faname,
        this.age = faage
    function Son(sonname,sonage,score){
            this.score = score

    var son = new Son('ldh',19,100)

Inherit parent type method

Error demonstration: son.prototype = father.prototype; This direct assignment will result in sharing a memory address and changing one to another.

Correct writing: son.prototype = new father();

If you modify the prototype object in the form of an object, you need to use constructor to refer back to the original constructor.

Son.prototype.constructor = Son;

ES5 new method

es5 has added some new methods to easily operate arrays or strings, mainly including:
Array method
String method
Object method

1. Array method


currentValue: the value of the current item of the array
Index: the index of the current item of the array
arr: array object itself


When function returns true, the filter returns the data and stores it in a new array.

  var arr = [12, 66, 4, 88, 3, 7];
  var newArr = arr.filter(function(value, index,array) {
  	 //Parameter 1: array element
     //Parameter 2 is the index of array elements
     //Parameter 3: current array
     return value >= 20;
  console.log(newArr);//[66,88] / / the return value is a new array


some looks up whether there are elements that meet the conditions in the array. The return value is a Boolean value. As long as an element that meets the conditions is found, return true will immediately terminate the loop

var arr = [10, 30, 4];
var flag = arr.some(function(value,index,array) {
    //Parameter 1: array element
     //Parameter 2 is the index of array elements
     //Parameter 3: current array
     return value < 3;

filter is also a search. It returns an array and returns all items that meet the conditions. some searches for a Boolean value and terminates when one is found. It is efficient.


The map() method returns a new array. The elements in the array are the values of the original array elements after calling the function.

Pass each element of the array to the specified function for processing and return the processed array, so ['1', '2', '3]. map(parseInt) takes string 1, 2 and 3 as elements; Call the parseInt function with 0, 1 and 2 as subscripts respectively. That is, the results of parseInt('1 ', 0), parseInt('2', 1) and parseInt('3 ', 2) are obtained respectively.

var numbers = [4, 9, 16, 25];

function myFunction() {
    x = document.getElementById("demo")
    x.innerHTML =;
//Result 2345


The every() method is used to detect whether all elements of the array meet the specified conditions (provided by the function).

The every() method detects all elements in the array using the specified function:

  • If an element in the array is detected to be unsatisfactory, the entire expression returns false and the remaining elements will not be detected.
  • Returns true if all elements meet the criteria.
var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;

function myFunction() {
    document.getElementById("demo").innerHTML = ages.every(checkAdult);
//Result: false

Finally, you need to use an array to receive new data.

Array method: usage difference between every() and some()

1. Every means

Conclusion: one false is false, and as long as one element is false, the following elements will no longer be traversed.

2.some() usage

Conclusion: one truth is true

3. Application scenarios of both

var computers = [
  { name: "mac", ram: 32 },
  { name: "mac", ram: 8 },
  { name: "IBM", ram: 16 },
  { name: "IBM", ram: 64 }
var everyComputerCan;
var someComputerCan;
//Determine whether the ram of each element is greater than 16
var everyBoolan = computers.every(function(item) {
  return item.ram > 16;
//Determine whether the ram of all elements is greater than 16
var someBoolean = computers.some(function(item) {
  return item.ram > 16;
console.log(everyBoolan); //Result: false
console.log(someBoolean);//Result: true

2. String method

Trim() removes spaces at the beginning and end of the string. value.trim();

3. Object method

1 .Object.keys(obj1)
Used to get all the properties (property name) of the object itself.
The effect is similar to for... in,
Returns an array of property names. var arr = Object.keys(obj1)

2 .Object.defineProperty()

Define new attributes in the object or modify the original attributes,
obj: target object, required
prop: defined or modified attribute. If not, add it. Required
descriptor: the attribute of the target attribute; required

Object.defineProperty(Object, modified or added property name,{
		value:The value of the modified or added property,
		writable:true/false,//If the value is false, this property value is not allowed to be modified
		enumerable: false,//enumerable if the value is false, traversal is not allowed
        configurable: false  //If configurable is false, it is not allowed to delete this attribute or whether the attribute can be modified again (the attribute here refers to the attributes written in braces, not the attribute itself)


delete obj1.a can delete the a attribute of obj1 and the value of this attribute.

Case query commodity price

        // Using the new array method to manipulate data
        var data = [{
            id: 1,
            pname: 'millet',
            price: 3999
        }, {
            id: 2,
            pname: 'oppo',
            price: 999
        }, {
            id: 3,
            pname: 'glory',
            price: 1299
        }, {
            id: 4,
            pname: 'Huawei',
            price: 1999
        }, ];
        // 1. Get the corresponding element
        var tbody = document.querySelector('tbody');
        var search_price = document.querySelector('.search-price');
        var start = document.querySelector('.start');
        var end = document.querySelector('.end');
        var product = document.querySelector('.product');
        var search_pro = document.querySelector('.search-pro');
        // 2. Render the data to the page
        function setDate(mydata) {
            // Clear the data in the original tbody first
            tbody.innerHTML = '';
            mydata.forEach(function(value) {
                // console.log(value);
                var tr = document.createElement('tr');
                tr.innerHTML = '<td>' + + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';

        // 3. Query goods by price
        // When we click the button, we can filter the objects in the array according to our commodity price
        search_price.addEventListener('click', function() {
            // alert(11);
            var newDate = data.filter(function(value) {
                return value.price >= start.value && value.price <= end.value;
            // Render the filtered objects to the page
        // 4. Search for goods according to their names
        // If the only element in the array is queried, some method is more appropriate, because if it finds this element, it will not cycle, which is more efficient]
        search_pro.addEventListener('click', function() {
            var arr = [];
            data.some(function(value) {
                if (value.pname === product.value) {
                    // console.log(value);
                    return true; // return must be followed by true  
            // Render the data to the page

JS AD 03 function advanced

Function definition method

1 custom function (named)
function fn() {};

2 function expression (anonymous function)
var fun = function() {};

3. Use newFunction('parameter 1 ',' parameter 2 ',' function body ');
var f = new Function();

var fn = new Function('a','b','console.log(a + b)');

The instanceof function detects whether the former belongs to the latter. Outputs a Boolean value.

console.log(fn instanceof Object );
//Detect whether fn is an object 
//Result: true

Everything in js is an object

Relationship between constructor f object instance and Function prototype object

function call

At present, six functions have been learned

1. Ordinary function fn ();

2. Object method obj1.sayHi()

3. Constructor new Star()

4. Bind event function btn.onclick=function() {} anonymous function

5. Timer function setInterval(function(),1000)

6. Execute the function (function() {} ()), (function() {}) () immediately

this points to the problem

1 ordinary functions point to window,
2. The method of the object points to the object,
3. The constructor points to the instantiated object,
4. The binding event function points to the binding event object,
5. The timer is completely written as window.setTimeout points to window,
6 immediately execute the function to point to window

js provides some function methods to handle this pointing, such as call(),apply(),bind()

1 .call(),arg1,arg2...)
Function 1 calls function 2 to change the direction of this
The main function is to realize inheritance

2 .apply()
It mainly calls a function. The difference from call is that the parameter is an array.

var arr1 = [1,2,3]
var max = Math.max.apply(null,arr1)
//The pointer here can point to null, preferably to Math itself

3 .bind()
Do not call the function, only change the internal this point of the function
Returns a copy of the original function modified by the specified this value and initialization parameters, that is, a modified function is returned

        var btn1 = document.querySelector('#btn1')

            this.disabled = true
                this.disabled = false

Strict mode

Safe, avoid ambiguity, reserve the keyword of ES6, strict

1. Script strict mode

Add a specific statement 'use strcit' before the script;

'use strict'; //The current script tag has strict mode turned on

    (function(){ //The strict mode is enabled in the current self calling function, and the normal mode is still outside the current function
    'use strict';

2 function strict mode

Open only within this function, and other functions are not affected

function fn() {
'use strict';

be careful:
1 in strict mode, you cannot use a variable without declaration.
2 delete is used to delete variables. In strict mode, declared variables cannot be deleted at will.
3 this pointing problem in strict mode: functions in the global scope, this pointing to undefine
4. If the constructor does not add a new call, this will report an error
5 in strict mode, the timer this still points to window

Functions in strict mode
1 cannot have duplicate name parameters
2. The function must be declared at the top level and cannot be written in if for

Higher order function

1 receive function as parameter 2 output function as return value
If any condition is satisfied, it is a higher-order function

The callback function is executed after all the previous parameters and code are executed.


A closure is a function that has access to a variable in the scope of another function.

To view the existence of closures in chrome:
F12 - > sources - > JS file - > right debugging area scope - > closure

Function is also a parameter type, so it can be returned as a parameter.

The function of closure extends the scope of variables.

The for loop is a synchronous task. After entering, it will directly execute the code in parentheses, but the contents in braces may be asynchronous, such as an onclick trigger event.

Closure case

        <li>Pork and celery dumplings</li>
        <li>Spanish mackerel cabbage dumplings</li>
        <li>Beef tomato dumplings</li>
        <li>Mutton carrot dumplings</li>
//Examples of errors:
    var lis = document.querySelectorAll('li')

        for(var i = 0;i<lis.length;i++){
//An error will be reported, mainly because setTimeout is an asynchronous task and i in for is synchronous. Direct execution results in i=4. Then the function in setTimeout is executed. lis does not have 4, so an error is reported.

//Correct example
        var lis = document.querySelectorAll('li')
        for (var i = 0; i < lis.length; i++) {
            (function (i) {
                setTimeout(function () {
                }, 3000)


You can call itself inside a function, which is a recursive function

Stack overflow due to dead recursion

Use return to return and set exit conditions

var num = 1;

  console.log('I want to print six sentences');
  if(num == 6)

Recursively find the factorial of 1-n

    function fun(n) {
            if (n == 1) {
                return 1
            return n * fun(n - 1)

        var num = fun(3)

Recursive calculation of layer 2 data

     var data = [{
            id: 1,
            name: 'jiadian',
            goods: [{
                id: 11,
                name: 'bingxiang'
                id: 22,
                name: 'kongtiao'
            id: 2,
            name: 'fushi'

        function getID(json, id) {
            var obj1 = {}
            json.forEach(function (item) {
                if ( == id) {
                    obj1 = item
                else if (item.goods && item.goods.length > 0) {
                    obj1 = getID(item.goods, id)
            return obj1
        console.log(getID(data, 11))


I have never known that javascript has a function similar to eq() in jQ. The original item() of native javascript has similar functions:

The following describes the usage of item():

Definition and Usage

The item() method the node at the specified index in the node list.

The following two grammars produce the same result:



Deep copy and shallow copy

Shallow copies copy only one layer, and deeper object level copies copy only references. If it is modified in the copy, it directly points to the data in memory through the address. After modification, the original object data is also modified.

Deep copy copies multiple layers, and each level of data is copied

Object.assign(targetobj,originalobj); Light copy syntax sugar ES6

Shallow copy:

//1 shallow copy with for loop
for( var k in obj){
  copy1[k] = oriObj[k]
//2 assign light copy

Deep copy:

        // Deep copy has multiple layers, and each level of data will be copied
        var obj = {
            id: 1,
            name: 'andy',
            msg: {
                age: 18
            color: ['pink', 'red']
        var o = {};
        // Encapsulation function 
        function deepCopy(newobj, oldobj) {
            for (var k in oldobj) {
                // Determine which data type our attribute value belongs to
                // 1. Get the attribute value oldobj[k]
                var item = oldobj[k];
                // 2. Judge whether the value is an array
                if (item instanceof Array) {
                    newobj[k] = [];
                    deepCopy(newobj[k], item)
                } else if (item instanceof Object) {
                    // 3. Judge whether this value is an object
                    newobj[k] = {};
                    deepCopy(newobj[k], item)
                } else {
                    // 4. It belongs to simple data type
                    newobj[k] = item;

        deepCopy(o, obj);

        var arr = [];
        console.log(arr instanceof Object);
        o.msg.age = 20;

JS AD 04

regular expression

regular expression, which is used to match the combination pattern of characters in a string. It's also an object. Can be used to validate forms, etc.

Create two ways

1 using the constructor of RegExp object
Var variable name = new regexp (/ expression /); var regExp=new RegExp(/123/)

2 literal creation
Var variable name = / /; var rg = /123/;

Test method ()

test() returns true or false. If the rule is met, it returns true; otherwise, it returns false.
1. Regexobj is a written regular expression rule
2. STR is the detected text

rule of grammar

Boundary character

^The start character, which should start with
$terminator, which should be used as the ending character

Character class

[] character set, indicating that there are a series of characters to choose from, as long as one of them is matched

 var rg1 = /^[a-z]$/;
 var rg1 = /^[a-zA-Z0-9-_]{3,16}$/;
//If there is a ^ in brackets, it means to take the opposite and cannot contain all the following contents
// console.log(rg1.test('b'));
// console.log(rg1.test('c'));
// console.log(rg1.test('abc'));


*Quantifier symbol, which specifies that the preceding character can appear 0 or many times, > = 0. var reg1 = //

+It is equivalent to 1 or many times, > = 1.

? Equivalent to 1 | 0

{n} Quantifier, the preceding character is repeated N times, {n,} more than n times, {n,m} n-m times

() indicates priority

Predefined Class

The or symbol in a regular is represented by a |.

The nickname is Chinese:/ 1{2,8}$/

Three detection methods


replace() [parameter / modifier]

g global match i ignore case

var str = document.getElementById("demo").innerHTML; 
var txt = str.replace(/microsoft/i,"Runoob");


var patt = /e/;
patt.test("The best things in life are free!");


The exec() method is a regular expression method that retrieves a match of regular expressions in a string.

This function returns an array containing matching results. If no match is found, the return value is null.

The following examples are used to search for the letter "e" in a string:

/e/.exec("The best things in life are free!");

JS AD 05 ES6

Standard Specification of js language

A new syntax for ES6

let keyword

With block level scope

Application scenario: 1. Prevent cyclic variables from becoming global variables; 2. There is no variable promotion; 3 has a temporary dead zone (that is, it is bound in the current scope, and the external will not affect its unavailability)

       let arr1 = [];
            for (let i = 0;i <2;i++){
                // var num = i;
                arr1[i] = function(){
                // arr1[i] = num;
            // console.log(arr1[1]);
            // console.log(arr1[0]);

Interview questions

Unused block level scope:

When the arr[i] statement is executed, only the data is assigned and a function is assigned, but the function is not called. During the following call, there is no definition of I variable in the function body, so the program looks up and finds the variable I that has been executed by the superior under the guidance of the scope chain. At this time, i = 2.

 var arr = [];
 for (var i = 0; i < 2; i++) {
     arr[i] = function () {
//The result is 2 

Use block level scope:

When calling, look for i from the superior, because i has block level scope, and each scope corresponds to a function, so each is its own.

 let arr = [];
 for (let i = 0; i < 2; i++) {
     arr[i] = function () {

const constant

The corresponding memory address cannot be changed, that is, the value cannot be changed.

Features: 1. It has block level scope. 2. The memory address cannot be changed. 3. It must be assigned when declared.

Simple data type, data cannot be modified.
Complex data type, memory address cannot be changed. Internal data can be modified, but the entire complex data type cannot be directly re assigned. Because reassignment requires rearrangement of memory addresses, it is not possible.

   const ary = [11, 22];
            ary[1] = 100;
            console.log(ary[1]);//Constant internal values can be changed
            ary = [100,200];// The error message does not allow the constant to be re assigned as a whole, and the memory address needs to be re allocated.

Destructuring assignment

Deconstruction: decomposes data structures.
ES6 allows you to extract values from an array and assign values to variables according to their corresponding positions. Objects can also be deconstructed.

Array deconstruction

One to one correspondence. If the received quantity is insufficient, the tail data of the original array will be discarded. If the received quantity is greater than the original array quantity, the part with insufficient received quantity is undefined

        let ary1 = [1, 2, 3]
        let [a, b] = ary1
        let ary1 = [1, 2, 3]
        let [a, b, c, d] = ary1

Object deconstruction

Two ways of writing

//This writing method needs to correspond to the attribute name in the original object one by one and cannot be modified
let person = { name: 'zhangsan' }
        let {name} = person
//Renamed writing
 let person = { name: 'zhangsan' }
        let {name:copyName} = person

Arrow function

Form: () = > {} function simplification function definition syntax
const fn = ()=>{}

If there is only one sentence of code in the function body. And the execution result of the code is the return value. Curly braces can be omitted.
If there is only one parameter, parentheses can be omitted.

const fn = v => alert(v)

This is not defined. It refers to this where the function defines the location context. Inherit the parent's this

Object cannot generate scope. The internal method is defined under the global scope.

An example of an interview question:

   var obj = {

The run result alert an undefined. Reason: the obj object has no scope, so it actually runs under the window object.

Verification Code:

var age=200  
var obj = {

Remaining parameters

If the number of arguments is greater than the formal parameters, the extra parameters are called residual parameters.
The residual parameter syntax allows us to represent an indefinite number of parameters as an array.

Three consecutive points have two meanings: spread operator and rest operator.

...: expand the operator to convert an array into a comma separated sequence of parameters


          const sum = (...args) => {
                let total = 0;
                args.forEach(item => total += item);
                return total;

           console.log(sum(10, 20)) 

In the function sum, three... Are added in front of the formal parameter args, which means that the remaining parameters can be accepted. After the previous formal parameters correspond to the arguments one by one, all the remaining arguments are accepted.


            let ary1 = ['zhangsan', 'lisi', 'wangwu'];
            for (var k in ary1) {
                //obj[k] gets the value in the attribute.

            let [s1,...s2] = ary1;

In this example, both residual parameters and structure assignment are used.

II. Built in object extension of ES6

Expansion method of ARRY

1 extension operator

The remaining parameters are placed in a formal parameter
The extension operator is to convert an array or object into a comma separated sequence of parameters.

Action 1 merge array

//Case 1	
arry3 = [...arry1,...arry2];
//Case 2 

Function 2: convert the class array into a true array

let oDivs = document.getElementsByTagName('div');
     var oDivs1 = [...oDivs];

2 Arry.from()

This is a constructor method.
Convert a class array or an object that can be traversed into a real array

    let arryLike = {
            for (var k in arryLike){
            var ary111 = Array.from(arryLike); 
            for (var k in ary1){

Array. From () can also receive the second parameter, which is similar to the map method of array. It is used to process each element, and the processed array is put into the returned array.

var ary2 = Arry1.from(arryLike,item=>item*2)

//The result is [0,2,4]

3 find()

Used to find the first qualified value in the array. If it is not found, it returns undefined

let arry1 = [{ id: 1, name: 'zhangsan' }, { id: 2, name: 'lisi' }]
let target = arry1.find(item => == 2)

4 findindex()

Find the first qualified position in the array. If it is not found, return - 1

5 includes()

Indicates whether an array contains a value. Returns a Boolean value. indexof is the old method

Template string

ES6 adds a new string creation method, which uses backquotes to define

let name = `This is a template string`

1 can resolve variable ${}

let name = `zhangsan`
let sayHello = `hello my name is ${name}`

2. The internal string can be wrapped, and the ordinary string cannot be wrapped

startsWith() and str.endsWith()

var str = 'hello world !'




The new data structure provided by ES6 is similar to an array. The internal members are unique and cannot be duplicated.

Set itself is a constructor that can accept an array as a parameter for initialization.

const s = new Set([1,2,3,4,4])

It also has the forEach method

The Set function can accept an array as a parameter for initialization.

const set = new Set([1, 2, 3, 4, 4]);//{1, 2, 3, 4}

Example method

  • add(value): adds a value and returns the Set structure itself
  • delete(value): deletes a value and returns a Boolean value indicating whether the deletion is successful
  • has(value): returns a Boolean value indicating whether the value is a member of Set
  • clear(): clear all members without return value
 const s = new Set();
 s.add(1).add(2).add(3); // Adds a value to the set structure 
 s.delete(2)             // Delete the 2 value in the set structure   
 s.has(1)                // Indicates whether there is 1 in the set structure. This value returns a Boolean value 
 s.clear()               // Clear all values in the set structure
 //Note: the value of the element is deleted, not the index


Like an array, an instance of a Set structure also has a forEach method to perform certain operations on each member without returning a value.

s.forEach(value => console.log(value))
  1. \u4e00-\u9fa5 ↩︎

Tags: Javascript node.js

Posted on Tue, 28 Sep 2021 23:19:25 -0400 by besbajah