当前位置:网站首页>JS high frequency interview questions

JS high frequency interview questions

2022-04-23 17:50:00 Front end more

JS

List of articles

data type

What is the basic data type ? What is a reference data type ? And how each data type is stored ?(5 star )

Basic data type :Number( The number )、String( character string )、Boolean( Boolean value )、Null( Null value )、Undefined( Undefined )、Symbol( Unique value )、

Reference data types are collectively referred to as Object adopt new Keyword created objects ( System object 、 Custom object ), Such as Object、Array、function, etc.
data type USONB You're so cool U:undefined S:string symbol O:object N:number null B:boolean
Data storage :
1. The data of the basic data type is stored directly in the stack ; and The reference data type only saves the reference address of the data in the stack , The real data is stored in the heap , This reference address points to the corresponding real data , In order to quickly find objects in heap memory .

2. Stack memory is allocated and released by the operating system . Heap memory is generally allocated and released by programmers , If programmers don't release , Recycling by garbage collection mechanism .

JS What are the built-in objects

The basic object Object, The built-in objects are Array Math Number String Date JSON

Type conversion

stay JS Why 0.2+0.1>0.3?(4 star )

Lies in JS Used in the IEEE 754 Double precision standard , When encoding data stored inside a computer ,0.1 It's not accurate at all inside the computer 0.1, But take an approximation 0.1. There is Lack of precision

// To decimal is exactly 0.30000000000000004

Why? 0.2+0.3=0.5 Well ?(4 star )

answer :0.2 and 0.3 They are converted to binary for calculation : stay JS The actual value in can only be stored 52 Last digit , They add up just before 52 The mantissa are all 0, Namely 0.5

since 0.1 No 0.1 了 , Why is it console.log(0.1) When it's still 0.1 Well ?(3 star )

stay console.log It will be converted from binary to decimal , Decimal will be converted to string form again , In the process of transformation, there is an approximation , So what you print out is a string of approximate values

Why? typeof null yes Object?(4 star )

  • Because in JavaScript in , If the first three bits of the binary are 0 Words , The system will judge it as Object type , and null The binary system of 0, Naturally, it is judged as Object

There are several ways to determine the type of data ?(5 star )

  • typeof

    • shortcoming :typeof null The value of is Object, I can't tell if it's null still Object
  • instanceof Determine whether an instance belongs to a certain type
    Object instanceof Object //true

    • shortcoming : We can only judge whether the object exists in the prototype chain of the target object , Can't judge the basic data type of literal quantity
  • Object.prototype.toString.call()

    • One of the best ways to detect basic types Object.prototype.toString.call() ; It can distinguish null 、 string 、boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math data type .

    • shortcoming : Can't be subdivided into whose instance

      // -----------------------------------------typeof
        typeof undefined // 'undefined' 
        typeof '10' // 'String' 
        typeof 10 // 'Number' 
        typeof false // 'Boolean' 
        typeof Symbol() // 'Symbol' 
        typeof Function // ‘function' 
        `typeof null // ‘Object’ `
        typeof [] // 'Object' 
        typeof {
          } // 'Object'
        // -----------------------------------------instanceof
        function Foo() {
           }
        var f1 = new Foo();
        var d = new Number(1)
        console.log(f1 instanceof Foo);// true
        console.log(d instanceof Number); //true
        console.log(123 instanceof Number); //false --> Can't judge the basic data type of literal quantity 
        // -----------------------------------------constructor
        var d = new Number(1)
        var e = 1
        function fn() {
          
          console.log("ming");
        }
        var date = new Date();
        var arr = [1, 2, 3];
        var reg = /[hbc]at/gi;
        console.log(e.constructor);//ƒ Number() { [native code] }
        console.log(e.constructor.name);//Number
        console.log(fn.constructor.name) // Function 
        console.log(date.constructor.name)// Date 
        console.log(arr.constructor.name) // Array 
        console.log(reg.constructor.name) // RegExp
        //-----------------------------------------Object.prototype.toString.call()
        console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" 
        console.log(Object.prototype.toString.call(null)); // "[object Null]" 
        console.log(Object.prototype.toString.call(123)); // "[object Number]" 
        console.log(Object.prototype.toString.call("abc")); // "[object String]" 
        console.log(Object.prototype.toString.call(true)); // "[object Boolean]" 
        function fn() {
          
          console.log("ming");
        }
        var date = new Date();
        var arr = [1, 2, 3];
        var reg = /[hbc]at/gi;
        console.log(Object.prototype.toString.call(fn));// "[object Function]" 
        console.log(Object.prototype.toString.call(date));// "[object Date]" 
        console.log(Object.prototype.toString.call(arr)); // "[object Array]"
        console.log(Object.prototype.toString.call(reg));// "[object RegExp]"
    

instanceof principle (5 star )

instanceof principle : Determine whether the object exists in the prototype chain of the target object , Look up layer by layer , Always find null until Extend to the prototype chain
a instanceof b a As object b For the target
a Whether it is b Instance object of

   function Foo() {
     }
    var f1 = new Foo();
    console.log(f1 instanceof Foo);// true
   function myInstance(L, R) {
    //L representative instanceof On the left ,R On the right 
      var RP = R.prototype
      var LP = L.__proto__
      while (true) {
    
        if(LP == null) {
    
          return false
        }
        if(LP == RP) {
    
          return true
        }
        LP = LP.__proto__ 
      }
    }
    console.log(myInstance({
    },Object)); 

null and undefined The difference between (4 star )

null:

  1. There should be no value here
  2. typeof null = object
  3. The value is 0
  4. As an argument to a function , The parameter representing the function is not an object ; As the end of the object prototype chain

undefined:

  1. There should be a value here, but it has not been defined yet
  2. typeof undefined = undefined
  3. The value is NaN
  4. For example, a variable is declared but not assigned a value , Is equal to undefined; Function has no return value default return undefined; Object has no assigned property , The value of this property is undefined

== and === What's the difference? ?(5 star )

The biggest difference is , Congruence does not perform type conversion .
Equality is the numeric equality after type conversion return true
The full number is represented by three equal signs (===), Only if the operands are equal without type conversion , To return to true

An exclamation mark plus two equal signs (!==) Express , Only if the operands are not equal without type conversion , To return to true.

== Equality in the strict sense of right and wrong ,

  • First check whether the data types are the same

  • If the same , Then compare whether the two numbers are equal

  • If the data types are different , First convert to the same data type , Further comparison .

    • Null == Undefined ->true
    • String == Number -> First the String To Number, Compare the size
    • Boolean == Number -> First the Boolean To Number, Comparing
    • Object == String,Number,Symbol -> Object Convert to primitive type
      === It's strictly equal , The data types and value sizes on both sides are compared
  • First check whether the data types are the same

  • If the same , Then compare whether they are equal , If equal return true

  • If different , Go straight back to false

1=='1'//ture
1==[1]//true
1==false//false
1==true//true

1==='1'//false
1===[1]//false

// special case 
null==undefined //true
null===undefined //false
NaN==NaN //false
NaN===NaN //false
//NaN(not a number) It's a special number , This value is used to indicate that an operand that is supposed to return a value does not return a value , Avoid reporting mistakes .NaN Not equal to any value , Include NaN Oneself .

Handwriting call、apply、bind (5 star )

call、apply、bind It's all about change this The way to point
call

fun. call (thisArg, argl, arg2, ..) 
thisArg: stay fun Specified by function runtime this value arg1,arg2: Other parameters passed 

call You can call functions directly , You can change the... In a function this Point to   
call The main role of inheritance can be achieved 
 var o = {
    name: 'andy'
  }
  function fn(a, b) {
    console.log(this)// Original this Point to window  When executed fn.call Point back o
    console.log(a + b)
  }
  fn.call(o, 1, 2)

bind
bind: Grammar and call As like as two peas , The difference is bind Don't call functions

fn.call(obj, 1, 2); //  change fn Medium this, And the fn Execute now 
fn.bind(obj, 1, 2); //  change fn Medium this,fn Not implemented   Wait for the event to trigger 

apply
and call Basically the same , The only difference is the way of passing parameters
apply Put it in an array ( Or class array ) Pass it in

fn.call(obj, 1, 2);
fn.apply(obj, [1, 2]);

Because we need to make all places accessible , So we write the custom function in Function On the prototype of , Because all the functions instanceof Function Will return true Of , So it's defined in Function Of prototype On call and bind We receive the second parameter after , So you may use slice Method , and apply Just accept the second parameter directly . So how to explicitly bind this Well , If the caller function , Owned by an object , Then when the function is called , Inside this Point to the object . Take the parameters , Let's use the simplest way arguments, Without parameters, we will directly return the function without parameters , If there is no incoming object, point directly to window, In this way, our handwriting function is the same as the original call,apply and bind It doesn't make any difference .

Function.prototype.MyCall = function(context){
// Put the function directly in Function Of prototype On , Convenient to call 
		const ctx = context || window;
// Here is to save the incoming object to ctx inside , If there is no incoming, it points to window, Because the original call The same thing 
		ctx.func = this;
// change this The direction of , In other words, it is equivalent to giving this function directly to the incoming object 
		const args = Array.from(arguments).slice(1);
// Here is to get the parameters of the function , After converting the class array into an array , Minus the first , Give to the args spare 
		const res = arguments.length > 1 ? ctx.func(...args) : ctx.func();
// That is, if there are parameters , hold args Deconstruction passes in , If you don't, you won't pass it on 
		delete ctx.func;
// At this time func It's no use anymore , Go straight back to res
		return res
// Step by step notes should be easy to understand 
	}

apply Follow call It's the same , It's just that the processing of parameters is simpler , There is no need to comment step by step .

Function.prototype.MyApply = function(context){
	const ctx = context || window;
	ctx.func = this;
	const res = arguments[1] ? ctx.func(...arguments[1]):ctx.func();
	delete ctx.func;
	return res
}

bind Somewhat different ,bind Function returns a binding function , The final call needs to pass in function arguments and bound function arguments . If the caller function , Owned by an object , Then when the function is called , Inside this Point to the object .

Function.prototype.MyBind = function(context){
	console cxt = JSOn.parse(JSON.stringify(context)) || window;
	cxt.func = this;
	const args = Array.from(arguments).slice(1);
	return function(){
		const allArgs = args.concat(Array.from(arguments));
		return allArgs.length > 0 ? cxt.func(...allArgs):cxt.func();
	}

Literal quantity creates objects and new What's the difference between creating objects ? Writing a new ?new What happened inside ?(5 star )

difference :

Literal :

var obj = {
    name: " Xiao Ming ",
    sayHi:function () {
        console.log(" I am a :" + this.name);
    },
   }
  • Literally, it's easier to create objects , Easy to read
  • No scope resolution is required , Faster

new: The process of creating objects is complex , This is the process

  • Create a new object
  • Make the new object __proto__ Point to the prototype object of the original function
  • change this Point to , Point to the new object and execute the function , The execution results are saved as result
  • Determine whether the result of executing the function is null or Undefined, If so, the previous new object is returned , If not, the previous execution result will be returned result

Handwriting new

    //  Writing a new
       var obj = new fn()
    function myNew(fn, arg) {
    
      //  Create an empty object 
      let obj = {
    }
      //  Make the implicit prototype of the empty object point to the explicit prototype of the original function 
      obj.__proto__ = fn.prototype
      // this Point to obj
      let result = fn.call(obj, arg)
      //  return 
      return result instanceof Object ? result : obj
    }
        console.log(null instanceof Object)//false
        console.log(undefined instanceof Object)//false

Literal sum new The objects and Object.create(null) What's the difference between the created objects ?(3 star )

  • Literal sum new The created object will inherit Object Methods and properties of , Their implicit prototypes point to Object An explicit prototype of ,
  • and Object.create(null) The object prototype created is null, As the top of the prototype chain , Naturally, there is no inheritance Object Methods and properties of

Prototype chain and prototype

What is a prototype ? What is prototype chain ? How to understand ?(5 star )

Prototype : Prototypes are divided into implicit prototypes (__proto__ attribute ) And explicit prototypes ( Prototype object prototype), Each object has an implicit prototype , It points to the explicit prototype of its own constructor .

Prototype chain : Multiple __proto__ The set of components becomes the prototype chain

Of instance objects __proto__ Point to constructor prototype object

Constructor prototype object __proto__ Point to Object Prototype object

Object Prototype object __proto__ Point to null

Every constructor has a prototype object prototype, Define all invariant methods directly on the prototype object , Then from the constructor new The instance object can Share these methods .
Instance objects will have __proto__ attribute , Point to the prototype object of the constructor prototype, The reason why instance objects can use constructors is that the properties and methods of prototype objects , It's because the object has __proto__ The existence of attributes .

Constructors .prototype === Instance object .__proto__

There is one of the prototype objects constructor attribute , Point to the original constructor

Sketch Map :

 Insert picture description here

JavaScript Member lookup mechanism (3 star )

1. When accessing the properties of an object ( Including method ) when , First, find out if the object itself has this property .

2. If not, look for its prototype ( That is to say __proto__ The prototype object of the constructor that points to )

3. If not, find the prototype of the prototype object ( namely Object Prototype object )

4. And so on all the time Object until (Object Prototype object __proto__=> The end point of the search mechanism is null).

5.__proto__ The significance of object prototype is to provide a direction for the search mechanism of object members , Or a route .

Execution stack and execution context

What is scope , What is scope chain ? (4 star )

  • Specifying the range of variables and functions that can be used is called Scope
  • When looking for variables or functions , You need to find... From local scope to global scope , The collection of these scopes is called Scope chain .
  • The function of scope chain is to ensure that the variables and functions with access in the execution environment are orderly , Variables in the scope chain can only be accessed up , Variable access to window Object is terminated

What is execution context , What is the execution stack ?(4 star )

Execution context ( That is, the execution environment of the code )

  • Global execution context

    Create a global window object , Also stipulates this Point to window, perform js Push it to the bottom of the stack , It pops up when the browser is closed

  • Function execution context

    Every time a function is called , Will create a new function execution context

  • eval Execution context

    eval Its function is to parse the corresponding string into JS Code and run

 Insert picture description here
Execution stack : With first in and last out structure , Used to store all execution contexts created during code execution

  • When entering an execution environment , It creates its execution context , And then press the stack , When program execution is complete , Its execution context will be destroyed , Play the stack .
  • The bottom of the stack is always the execution context of the global environment , At the top of the stack is always the execution context of the function being executed
  • The global execution context will pop up only when the browser is closed

Closure

What is a closure ? The function of closures ? Application of closures ? (5 star )

Variables under the outer scope can be obtained under the inner scope , The variables under the outer scope cannot be obtained under the inner scope
And the emergence of closures , That solves the problem
The internal function references the parameters and local variables of the external function , be called Closure , It can be understood as “ A function defined inside a function ”
Global variables can be obtained anywhere , Local variables can only be obtained inside a function

( Global variables can be read directly inside the function , However, local variables inside the function cannot be read outside the function . There is a place to pay attention to , When variables are declared inside a function , Be sure to use var command . If not , You actually declare a global variable !)

characteristic :
Function nesting within function
Inner functions can reference outer parameters and variables
Parameters and variables are not recycled by the garbage collection mechanism
effect
Can realize encapsulation and caching , Avoid pollution of global variables

shortcoming :
Memory consumption 、 Improper use will cause memory leakage ( There's a block of memory that's been occupied for a long time , Without being released )
The solution is , Before exiting the function , Delete all unused local variables
application

  • Anti shake and throttling

  • Encapsulate private variables

  • for Retention in the loop i The operation of

  • JS The singleton pattern in the design pattern

    The singleton pattern : Use a variable to indicate whether an object has been created for a class , If it is , The next time you get an instance of this class , Return directly to the previously created object

  • The function is coriolized

Basic step analysis :

  1. Define external functions , Variables to be protected and internal functions that can be accessed externally . Operate on protected variables through internal functions , And return the inner function to .
  2. Call the external function to get the internal function , The protected variables are then manipulated based on internal functions .
    function outer() {
    // External function 
      var count = 0; // Protected variables ( This variable cannot be used directly outside )
      return function () {
    // Internal function 
        count++; // Operate on protected variables through internal functions 
        console.log(count);
      };
    }// The whole function above is closure design 
    var inner = outer(); // Call the external function to get the internal function 
    // Anonymous function as outer The return value of is assigned to inner amount to inner=function () { count++; console.log(count);} 
    // Anonymous functions are given global variables , And the anonymous function references outer Variables in functions count, So the variable count Cannot be destroyed 

    inner(); // Call internal functions to operate on protected variables 

1. Closure as return value

 Insert picture description here
In this code ,a() The return value in is an anonymous function , This function is in the a() Within scope , So it can get a() Variable under scope name Value , Assign this value as the return value to the variable under the global scope b, The value of the variable in the local variable is obtained under the global variable

 Insert picture description here
In general , In function fn After the execution , It should be destroyed together with the variables in it , But in this case , Anonymous function as fn The return value of is assigned to fn1, This is equivalent to fn1=function(){var n = 0 … }, And the anonymous function references fn Variables in num, So the variable num Cannot be destroyed , Variables n It's created every time it's called , So every time fn1 After execution, it destroys its own variables together with itself , So in the end, it was left alone num, So here comes the problem of memory consumption
return function As long as the function meets return Just return the following result to the caller of the function

2. Closures as parameters
 Insert picture description here
In this code , function fn1 Passed as a parameter into the immediate execution function , In carrying out the fn2(30) When ,30 Pass in as a parameter fn1 in , Now if(x>num) Medium num What is taken is not the immediate execution of... In the function num, Instead, take the... In the scope where the function is created num The scope created by the function here is under the global scope , therefore num Take the value in the global scope 15, namely 30>15, Print 30

     var a = 1,
        b = 0;
      function A(a) {
    
        A = function (b) {
    
          alert(a + b++);
        };
        alert(a++);
      }
      A(1);//'1'
      A(2);//'4'

function A Medium A of no avail var Statement , So it belongs to global variable , Rewrite the assignment function A, It's a closure again

Closure mechanism : After the closure is created , You can save the active object at the time of creation .
Self addition operator :i++ Execute first and then add ,++i First add to the execution . Such as var a = 0; var b = 1; var c = a+b++,console.log(c,b) // 1 2

First call to function A when , The function does not call and does not execute itself , therefore A = function (b) {alert(a + b++);} No implementation , Execute to alert(a++) when ,a++ Execute first and add later , therefore a++ by 1,a by 2, so A(1)=‘1’

The second call to the function A when ,A Covering functions A;

Because of the identifier A Is defined in the global scope , So it is reassigned inside the function , The reassigned function can also be accessed in the global scope . here , Also created a closure , This closure holds the active object that creates the environment .

Execute to A(2), namely b=2,alert(a + b++)=‘4’,A(2) Output ’4’

Inherit

say JS What are the common inheritance methods in ? And the advantages and disadvantages of each inheritance method (5 star )

By inheritance , Subclasses can not only have the methods and properties of the parent class, but also add new properties and methods or modify the properties and methods of the parent class .
answer :
Prototype chain inheritance , Is to connect object instances through prototype chain , When accessing a property of the target object , Can follow the prototype chain to find , So as to achieve the effect similar to inheritance .
The prototype object of the child is new An instance of a parent Son.prototype = new Father(‘zs’);

function Father(name) {
  this.name = name;
}
Father.prototype.money = function () {
  console.log(1000);
};
function Son() {}
Son.prototype = new Father('zs');
var son = new Son('zs');
console.log(son.name);
son.money();

shortcoming : When an instance modifies an attribute on the prototype chain , If the instance type is a reference type , Then the properties of other instances will also be modified .

Borrow the constructor to inherit the parent type attribute
principle : adopt call() Put the parent type of this Pointing to a subtype this, In this way, the child type can inherit the properties of the parent type

 function Father(name) {
    this.name = name;
 }

 function Son(name) {
    Father.call(this,name);// At this point, the parent class this To subclass this  And call the function 
 }

var son= new Son('zs');
 console.log(son.name);//zs

shortcoming : Cannot inherit properties on the parent prototype chain

Combination inheritance

The method of inheritance and sharing using prototype chain , Inherit instance properties by borrowing constructors
principle : Use... In subclass constructors Parent.call(this); The method can be inherited and written in the parent class constructor this The properties and methods bound on ;

  
function Child(name,age){
    
    //  Inheritance attribute 
    Parent.call(this, name)
    this.age=age
}
//  Inheritance method 
Child.prototype = new Parent()
Child.prototype.constructor = Child;

es6 extend Inherit

es6 class Implementation inheritance uses keywords extend Indicates which parent class to inherit from , And... Must be called in the subclass constructor super keyword ,super Keyword is used to access and call functions on the object's parent class .

    //  The subclass only inherits the parent class , Don't write constructor, Once it's written , It's in constructor  The first sentence in the must be  super
    class Son3 extend Father {
    
      constructor(y) {
    
        super(200)  // super(200) => Father.call(this,200)
        this.y = y
      }
    }

Memory leak 、 Garbage collection mechanism

What is memory leak ? (5 star )

answer :

A memory leak is when memory that is no longer in use is not released in time , This section of memory cannot be used

Why does it lead to a memory leak ? (5 star )

answer :
We can't pass through a certain section of memory js Access an object , The garbage collection mechanism thinks that the object is still being referenced , So the garbage collection mechanism doesn't release the object , This block of memory can never be released , Many a little make a mickle , The system will get more and more stuck and crash

What operations can cause memory leaks ?(4 star )

  • not used var Declared global variables

  • Scope not released ( Closure )

  • Timer not cleared

  • Event monitoring is blank

    How to optimize ?

    1. Global variables are declared in use first
    2. Avoid using closures too much .
    3. Pay attention to clearing the timer and event listener .

What strategies do garbage collection mechanisms have ? (5 star )

Garbage collection mechanism : When a program creates an object , When referencing type entities such as arrays , The system will allocate a memory area in the heap memory , The object is stored in the memory area , When memory is no longer referenced by any reference variable , This memory becomes garbage , Wait for the garbage collection mechanism to recycle .

( understand ) The objects of the new generation are the ones with shorter survival time , Objects in an old generation are objects that have a long life or are memory resident .V8 A generational recycling strategy was adopted , Divide memory into two generations : The new generation and the old generation

New generation algorithm :GC Copy algorithm

Divide the memory into two spaces of the same size From and To, utilize From Space is allocated , When From When the space is full ,GC Copy the surviving objects to To Space , And then put From Clean up the space at one time , After that, the two spaces are exchanged GC( Garbage collection )

Old generation algorithm : Tag clearing algorithm

The garbage collector will mark all variables in memory when running , Then remove the variables in the execution environment and the variables referenced by the variables in the execution environment ( Closure ), After all this is done, the variables that are still marked are the ones to be deleted

answer :

  • Mark removal method

    • The garbage collector will mark all variables in memory when running , Then remove the variables in the execution environment and the variables referenced by the variables in the execution environment ( Closure ), After all this is done, the variables that are still marked are the ones to be deleted
  • Reference counting

    ​ principle : Track the number of times each value is referenced , When the count changes to 0 When , Indicates that the value cannot be accessed , The garbage collection mechanism clears the object .

    • When you declare a variable and assign it a value of a reference type , The count of this value +1, When the value is assigned to another variable , The count +1, When the value is replaced by another value , The count -1, When the count changes to 0 When , Indicates that the value cannot be accessed , The garbage collection mechanism clears the object

Deep copy and light copy (5 star )

Shallow copy Only the first layer of the object is cloned , Common objects are 3-4 layer , If the object is multidimensional , That is, two-dimensional and above objects . It needs to be used Deep copy Methods . Shallow copy copies an object's attributes and attribute values to another object

let obj = {
    
    a: 100,
    b:[10,20,30],
    c:{
    
        x:10
    },
    d: /^\d+$/
}

Shallow copy

Shallow copy Because objects will only be copied to the outermost layer , As for deeper objects , It still points to the same heap memory by reference , This results in if the new object is modified , It will also affect the original object

Method 1: Use the deconstruction of objects

Object's extension operator (…) Used to fetch all traversable properties of the object , Copy to current object .

let obj2 = {
    ...obj}

Method 2: Using a loop

Object loop we use for in loop , but for in The loop will traverse the inherited properties of the object , We just need its private properties , So you can add a judgment method :hasOwnProperty Keep object private properties hasOwnProperty() Method only detects the current object itself , Returns... Only if the property exists in the current object itself true,

let obj2 = {
    }
for (let i in obj){
    
    if(!obj.hasOwnProperty(i)) break;  //  Use here continue It's fine too 
    obj2[i] = obj[i]
}

Deep copy

Method 1:_.cloneDeep

lodash Provides _.cloneDeep Method for deep copy

let deep = _.cloneDeep(obj)
console.log(deep === obj) //false

Method 2:JSON.stringify,JSON.parse

let obj2 = JSON.parse(JSON.stringify(obj))

The problem is : If you encounter a regular object, it will become an empty object , Function is empty , The date will change to a string

Method 3: Omnipotent method

First, filter special cases =null Type does not belong to Object And remove the regular then for in loop utilize hasOwnProperty Get the inheritance properties of the object

function deepClone(obj){
    
    // Filter special cases 
    if(obj === null) return null;
    if(typeOf obj !== "Object") return obj;
    if(obj instanceof RegExp){
    
        return new RegExp(obj)
    }
    // The purpose of not directly creating an empty object is to keep the copied result the same class as before 
    let newObj = new Obj.constructor 
    // You can write like this :
    //let newObj = obj instanceof Array?[]:{}
    for (let i in obj){
    
        if(obj.hasOwnProperty(i)){
    
            newObj[i] = deepClone(obj[i])
        }
    }
    return newObj;
}
let obj2 = deepClone(obj)
console.log(obj.c === obj2.c) //fasle  Indicates a different memory point to 

The event loop Event Loop

Why? JS It's single threaded ?(5 star )

because JS There's something visible in it Dom, If it's multithreaded , This thread is being deleted DOM node , Another thread is editing Dom node , The browser doesn't know who to listen to

Asynchronous execution mechanism (5 star )

JS Asynchrony of is realized by callback function
generally speaking , There are three types of asynchronous tasks
1、 Ordinary events , Such as click、resize etc.
2、 Resource loading , Such as load、error etc.
3、 Timer , Include setinterval、setTimeout etc.
Asynchronous task related callback functions are added to the task queue ( Task queues are also known as message queues ).

The event loop :

(1) All synchronization tasks are performed on the main thread , To form a Execution stack (execution context stack).

(2) Outside the main thread , There is also a Task queue (task queue). As long as asynchronous tasks have run results , It's just ’‘ Task queue ’' Put an event .

(3) once " Execution stack " All synchronization tasks in are completed , The system will read " Task queue ", Asynchronous task state , Enter the execution stack , Start execution . The main thread is from " Task queue " Read events in , This process is cyclical , This execution mechanism is called an event loop .
 Insert picture description here

Stack : First in, then out

queue : fifo

Linked list : adopt .next Connect nodes in series

Specific execution sequence :

  1. When the main thread runs, it will generate a heap (heap) And the stack (stack);
  2. js Top to bottom parsing method , Arrange the synchronization tasks into the execution stack according to the execution order ;
  3. When the program calls an external API when , such as ajax、setTimeout etc. , Such asynchronous tasks are suspended , Continue to execute the tasks in the stack , After the asynchronous task returns the result , Then it is arranged in the event queue according to the execution order ;
  4. The main thread first empties the synchronization task in the execution stack , Then check whether there are tasks in the event queue , If there is , Push the callback corresponding to the first event to the execution stack for execution , If an asynchronous task is encountered during execution , Then continue to arrange the asynchronous task into the event queue .
  5. Every time the main thread empties the execution stack , Go to the event queue and check whether there are tasks , If there is , Just take out one at a time and push it to the execution stack for execution , This process is cyclical .

Macro task and micro task (5 star )

Macro task :setTimeout,setInterval,setImmediate,I/O,UI Interactive events , Event binding
setImmediate This method is used to put some long-running operations into a callback function , After the browser completes the following statements , Just execute the callback function immediately ,

Micro task :Promise.then,process.nextTick(node)

In the same event cycle , Micro tasks always execute before macro tasks .

Order of task execution ?( important )

1. Queue the synchronization task to the execution stack , Asynchronous tasks are queued to the task queue .

2. When executing a method in a browser environment , First clear the synchronization task in the execution stack , Then push the micro task to the execution stack and empty , Then check whether there are tasks , If it exists, take out a macro task , Check whether there are micro tasks after execution , In this cycle …

3.Event Loop In the browser with node Differences in the environment :

  • ​ The browser environment executes one macro task at a time , Just check the micro task
  • ​ node The queue of the current stage will be cleared , That is, execute all task( Macro task ), Then check the micro task ,node11 edition Event Loop The operating principle has changed , Consistent with browser .

Promise async/await Execution process (3 star )

Promise and async Immediate execution in :

Promise Asynchrony in then and catch in , So it's written in Promise The code in is executed immediately as a synchronization task .

And in the async/await in , stay await Before appearance , The code is also executed immediately . await+ After the expression is executed, you can continue to execute other code in the function

and await + The expression will be executed first , take await + expression The following code is added to Micro tasks , And then it will jump out of the whole async Function to execute the following code . therefore await + The code behind the expression is a micro task .

case analysis (5 star )

Case a

  console.log(1);
    setTimeout(() => {
    
      console.log("setTimeout"); 
      let promise1 = new Promise((resolve) => {
    
          console.log(2); 
          resolve();
        })
        .then((data) => {
    
          console.log(100); 
        })
    }, 10);
    setTimeout(() => {
    
      console.log("setTimeout1"); 
      let promise1 = new Promise((resolve) => {
    
          console.log(3); 
          resolve();
        })
        .then((data) => {
    
          console.log(200); 
        })
    }, 0);// Pay attention to the time sequence 
    let promise = new Promise((resolve) => {
    
        console.log(4); 
        resolve();
      })
      .then((data) => {
    
        console.log(500);
      })
      .then((data) => {
    
        console.log(600);
      });
    console.log(7); 
    //1 4 7 500 600 setTimeout1 3 200 setTimeout 2 100

setTimeout(() => {
    
  console.log(1)
}, 0);
const p = new Promise((resolve, reject) => {
    
    console.log(2);
    setTimeout(() => {
    
      resolve()
      console.log(3)
    }, 0);
  })
  .then(() => {
    
    console.log(4)
  })
console.log(5)//2 5 1 3 4  meet resolve() To perform .then

above , according to js Top to bottom execution sequence , In case of synchronization task, output 1.setTimeout It's a macro task , It will be put into the macro task queue first . and new Promise It's immediate , So it will output 4. and Promise.then It's a micro task , Will be arranged in the micro task queue in turn , Continue to perform output down 7. Now the tasks in the execution stack have been cleared , Then empty the micro task queue , Output... In sequence 500 and 700. Then take out the first macro task , Output setTimeout1, Execute one macro task at a time , Then check the micro task , Output setTimeout1、3 、200. Then take out the output of the second macro task setTimeout, Then check the micro task , Output setTimeout 、2 、100.

Case 2

//node In the environment 
setImmediate(() => {
    
   console.log(1);
   process.nextTick(() => {
    
     console.log(4);
   });
 });
 process.nextTick(() => {
    
   console.log(2);
   setImmediate(() => {
    
     console.log(3);
   });
 });

js Follow the execution order from top to bottom , take setImmediate Line up to node Event ring I/O callbacks In line ,process.nextTick Arrange to micro task queue . First check the execution stack , Found no mission , Then check the micro task queue and empty it , Output 2, And will setImmediate Line up to I/O callbacks queue , Check timers queue , Found no mission , To continue to check I/O callbacks queue , Found a mission , Perform emptying , Output 1, take process.nextTick Arrange to micro task queue , Carry on , Output 3, Finally, empty the micro task , Output 4.

Case three

// Function does not call   Events do not execute 
async function async1(){
    
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
    
  console.log("async2");
}
console.log("script start"); 
setTimeout(function () {
    
  console.log("setTimeout");
}, 
async1();
new Promise(function (resolve) {
    
  console.log("promise1");
  resolve();
}).then(function () {
    
  console.log("promise2");
});
console.log("script end");
//script start/async1 start/async2/promise1/script end/async1 end/promise2/setTimeout
  1. We see that we first define two async function , So let's look down , Then I met console sentence , Direct output script start. After output ,script The mission goes on , encounter setTimeout, As a macro task , Then its tasks will be distributed to the corresponding queue first

  2. script The mission goes on , Yes async1() function , async Function in await The previous code was executed immediately , So it will immediately output async1 start. Yes await when , Will await The following expressions are executed once , So it's followed by the output async2, And then await The following code is console.log('async1 end') Add to In micro tasks Promise In line , Then jump out async1 Function to execute the following code .

  3. script The mission goes on , encounter Promise example . because Promise The functions in are executed immediately , And the subsequent .then Will be distributed to The task of micro Promise The queue to . So it will output promise1, And then execute resolve, take promise2 Assigned to the corresponding queue .

  4. script The mission goes on , Finally, only one sentence is output script end, thus , The global task is finished .
    stay script After task execution , Start searching, clear the micro task queue . here , Micro tasks , Promise There are two tasks in the queue async1 end and promise2, So output in order async1 end,promise2.

  5. Finally, execute the macro task , only one setTimeout, Take out the direct output , So far the whole process is over .

At the first time macrotask After execution , That is output script end after , Will clean up all microtask. So it will output one after another promise2, async1 end ,promise4, I won't say more about the rest .

Case four

async function a1 () {
    
    console.log('a1 start')//2
    await a2()
    console.log('a1 end')// tiny 2 7
}
async function a2 () {
    
    console.log('a2')//3
}
console.log('script start')//1
setTimeout(() ={
    
    console.log('setTimeout')
}, 0)// macro 1 10
Promise.resolve().then(() ={
    
    console.log('promise1')
})// tiny 1 6
a1()
let promise2 = new Promise((resolve) ={
    
// Convert an existing object to  Promise  object 
    resolve('promise2.then')// tiny 3 8
    console.log('promise2')//4
})
promise2.then((res) ={
    
    console.log(res)
    Promise.resolve().then(() ={
    
        console.log('promise3')// tiny 4 9
    })
})
console.log('script end')//5
//script start/a1 start/a2/promise2/script end/promise1/a1 end/promise2.then/promise3/setTimeout

Case 5

  setTimeout(() => {
    
      console.log('1');//5
      new Promise(function (resolve, reject) {
    
        console.log('2');//6
        setTimeout(() => {
    
          console.log('3'); //9
        }, 0);
        resolve();
      }).then(function () {
    
        console.log('4')//7
      })
    }, 0);// macro 1
    console.log('5'); //1
    setTimeout(() => {
    
      console.log('6');//8
    }, 0); // macro 2
    new Promise(function (resolve, reject) {
    
      console.log('7');//2
      // reject();
      resolve();
    }).then(function () {
    
      console.log('8')// tiny 1 4
    }).catch(function () {
    
    //catch stay Promise Status as rejected When the ,then Methods capture Promise The status of is rejected, Is executed catch Operation in method 
      console.log('9')                                                       
    })
    console.log('10');//3
//5 7 10 8 1 2 4 6 3

Case 6

 for (var i = 0; i < 5; i++) {
    
        setTimeout(function () {
    
          console.log(i++);//5 6 7 8 9
        }, 1000);
      }
      console.log(i);//5

 Insert picture description here

First execute the task on the main thread ,for Circulation and console.log(i), Every time for Loop to add a macro task into the task queue , The order of execution results is console.log(i);//5 i++=5,i++=6,i++=7,i++=8,i++=9 i++ The first operation is adding

summary : Task execution , Go through the whole first , Synchronization tasks are executed sequentially in the main thread , In asynchronous tasks, micro tasks are always executed before macro tasks , Sort out the order in which they enter the task queue , Micro and macro tasks in the main thread come first .

ES6

ES6 New characteristics

How can variables and functions be promoted ? What's the priority ?(4 star )

stay ES6 Before ,JavaScript There is no block-level scope ( A pair of curly braces {} Is a block level scope ), Only global scope and function scope .
Variable Promotion : The declaration of the variable will be promoted to the top of the current scope , The assignment of variables does not increase

  • Lifting variables , Only declare , No assignment , The value is undefined

Function enhancement : The declaration of the function will be promoted to the top of the current scope , But it doesn't call the function

  • Open up space

  • Store content

  • Assign an address to a variable

  • Function promotion takes precedence over variable promotion

 // Variable Promotion : The declaration of the variable will be promoted to the top of the current scope , The assignment of variables does not increase 
    var fn = function () {
    
      console.log(1);
    }
    fn();
    //=> var fn;
    // fn();
    // fn=function(){
    
    // console.log(1);
    // }
    // Function enhancement : The declaration of the function will be promoted to the top of the current scope , But it doesn't call the function 
    fn();

    function fn() {
    
      console.log(1);
    }
    //=> function fn() {
    
    // console.log(1);
    // }
    // fn();

 // Case study 1
 function Foo() {
    
      getName = function () {
    
        console.log(1);
      }
      return this;
    }
    Foo.getName = function () {
    
      console.log(2);
    }
    Foo.prototype.getName = function () {
    
      console.log(3);
    }
    var getName = function () {
    
      console.log(4);
    }

    function getName() {
    
      console.log(5)
    }
    // Variable Promotion 
    //[1]function Foo() {
    
    // getName = function () {
    
    // console.log(1);
    // }
    // return this;//window
    // }
    //[2]var getName;
    //[3]function getName() {
    
    // console.log(5)
    // }
    //[4]Foo.getName = function () {
    
    // console.log(2);
    // }
    //[5]Foo.prototype.getName = function () {
    
    // console.log(3);
    // }
    //[6]getName= function () {
    
    // console.log(4);
    // }
// Operation type priority  new( With parameter list )>new( No parameter list ))
    Foo.getName(); //2 [4]Foo.getName() Is a simple expression   Output function  Foo Static method of , So direct output 2
    getName(); //4 [6] getName() For reasons stated in advance ,  After the declaration was  var getNmae() = xxx  Covered with   So the output here   become  4
    Foo().getName(); //1  Execute first Foo(), Inside return this  yes window, namely Foo().getName() become window.getName  stay Foo The global variable inside getName Cover , So the output is  1
    getName(); //1  ditto  1
    new Foo.getName();//2 [4]new 18 Foo.getName() 19 , First Foo.getName() stay new, by 2
    new Foo().getName(); //3 [5]new Foo() 19 Foo.getName() 19  The priority is the same, from left to right , First new Foo() stay getName(),new Foo() Create examples ,xxx.getName() The archetypal approach   by 3
    new new Foo().getName(); //3 [5] First new Foo().getName() new(new Foo().getName)new Foo() Create examples ,xxx.getName() The archetypal approach   by 3

var let const What's the difference? ? (5 star )

  • var Declaration variable has variable promotion ,let and const non-existent
  • var Will be with window Phase mapping ( Will hang a property ), and let Not with window Phase mapping
  • var The scope of the function is the scope of the function , and let、const The scope of is block level scope
  • Under the same scope var Variables can be declared repeatedly , and let const Sure
  • In the same scope let and const There will be a temporary dead zone before declaration , That is to say let、const Before the statement , Variables cannot be used
  • const
    • const Once a constant is defined, it must be assigned a value , Declared value ( Memory address ) You can't modify ,const The memory address pointed to by the declared constant cannot be modified , But you can change the internal properties

Arrow function , And the difference from ordinary functions , Arrow functions can be used as constructors new Do you ? The function of the arrow function (5 star )

Arrow function ()=>{}:

  1. If there is only one parameter , Then brackets can be omitted ;
  2. If there is only one statement in the function body , The curly braces can be omitted , The return value of the function is the execution result of the statement ;

The difference from ordinary functions

  1. Ordinary functions have function promotion , The arrow function does not
  2. Arrow functions don't have their own this,arguments, Arrowhead function this Point to parent ( Look for the outer scope ): First, find... From its parent scope , If the parent scope is still an arrow function , Look up again , Until I find this The direction of .
  3. Arrow function cannot be a constructor , in other words , Not available new command ( No, this), Otherwise, an error will be thrown .
  4. No, yield attribute , Cannot be used as a generator Generator function

Arrow function cannot new

  • There is no one's own this, Cannot call call and apply
  • No, prototype,new Keyword internal need to put the new object's _proto_ Pointing to a function prototype

The function of the arrow function :

1. Grammatical simplicity

2. Can implicitly return

// Show return 
const double3 = numbers.map(number => {
    
    return number * 2;  
})
// Implicit return 
// Get rid of return And curly braces , Move the returned content to one line , More concise ;
const double3 = numbers.map(number => number * 2);

3. No binding this

this Is actually inherited from its parent scope this, Of the arrow function itself this It doesn't exist , This is equivalent to the arrow function this It was determined at the time of the statement ,this The direction of does not change with the call of the method

Promise( What is? Promise?)

Be able to write Promise/all function

Promise :ES6 The introduction of a new solution to asynchronous programming , Grammar is a Constructors , Used to encapsulate asynchronous operations and obtain the results of their success or failure . Promise Objects have three states : initialization pending success fulfilled Failure rejected

  • Promise It's an object , Used to represent and pass the final result of asynchronous operation
  • Promise {: PromiseResult} PromiseState: state PromiseResult: Return value
  • Promise The main way of interaction : Pass the callback function into then Method to get the final result or the cause of the error
  • Promise Performance in code writing : With “ call chaining ” Instead of the callback function, it is nested layer by layer ( Back to hell )p.then().then()

When we're building Promise When , The code inside the constructor is Execute now Of .Promise The constructor is the main thread , and Promise.then It's a micro task . call resolve This promise The status of the object is successful , call reject This promise The state of the object is failed

new Promise((resolve, reject) => {
    
  console.log('new Promise');
  // Status is success 
  resolve('success');
});
console.log('finifsh');

//  Print first new Promise,  Re print  finifsh

call Promise Object's then Method , The two parameters are functions , The return is promise object , The object state is determined by the execution result of the callback function .

	// establish Promis object 
	const p = new Promise((resolve, reject) => {
    
        setTimeout(() => {
    
          resolve(" success ");
        }, 1000);
      });
  
      //1. If the return result in the callback function is   Not promise object , Status is success , The return value is the object success value fulfilled
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          return 1;
        },
        (reason) => {
    }
      );
      console.log(result); //Promise {<fulfilled>: 1}
-------------------------------------------------------------------------------------------
      //2. If the return result in the callback function is promise object , this promise The object determines the above promise object p The state of 
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          return new Promise((resolve, reject) => {
    
            resolve("ok"); 
            reject("err"); 
          });
        },
        (reason) => {
    }
      );
      console.log(result);// //Promise {<fulfilled>: 'ok} Promise {<rejected>: 'err'} 
-------------------------------------------------------------------------------------------
      //3. Throw an error 
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          throw " Error "; 
        },
        (reason) => {
    }
      );
      console.log(result); // Promise {<rejected>: ' Error '} 

​ Promise Realized call chaining , That is to say, every call then After that, all the people who returned were Promise, And it's a brand new Promise, The reason is that the state is immutable . If you are in the then in Used return, that return The value of will be Promise.resolve() packing . Promise.resolve() Convert the object to promise object

Promise.resolve(1)
  .then((res) => {
    
    console.log(res); // => 1
    return 2; //  Package as  Promise.resolve(2)
  })
  .then((res) => {
    
    console.log(res); // => 2
  });

Promise It's also a good solution Back to hell The problem of .

Back to hell :` Callback functions are nested layer by layer , Low code readability 、 Inconvenient for later maintenance

ajax(url)
  .then((res) => {
    
    console.log(res);
    return ajax(url1);
  })
  .then((res) => {
    
    console.log(res);
    return ajax(url2);
  })
  .then((res) => console.log(res));
// Writing a Promise
const promise = new Promise(function (resolve, reject) {
    
  if (true) {
    
    resolve(value)
  } else {
    
    reject(error)
  }
})
promise.then(res => {
    
  console.log(res)
}).catch(err => {
    
  console.log(err)
})

async and await(3 star )

async and await The combination of the two syntax can make asynchronous code look like synchronous code , Simplify the writing of asynchronous functions

async function :

1.async The return value of the function is promise object ;

2.promise The result of the object is determined by async The return value of the function execution determines

3.async yes Generator Grammatical sugar of function , Also on Generator The function is improved , It's right yield Simple encapsulation

    async function fn() {
    
      //1. If the return result is   Not promise object , Status is success , The return value is the object success value fulfilled
      return 123;
      //2. Throw an error 
      throw " Error ";
    }
    const result = fn();
    console.log(result); // Promise {<fulfilled>: 123} Promise {<rejected>: ' Error '}
-----------------------------------------------------------------------------------------
    async function fn() {
    
      //3. If returned promise object , Then the final result is Promise object 
      return new Promise((reslove, reject) => {
    
        //resolve(' success ');
        reject(' Failure ');
      })
    }
    const result = fn();
    console.log(result); //Promise {<rejected>: ' Failure '}
    // then Method to get the final result or the cause of the error 
    result.then(
      (value) => {
    
        console.log(value);
      },
      (reason) => {
    
        console.log(reason); // Failure 
      }
    )

await expression :

1.await Must be written in aysnc Function ;

2.await The following expression is generally Promise object ;

3.await The return is Promise The value of success ;

4.await Of Promise failed , Will throw an exception , Unable to deal with promise Back to reject object , Need to pass through try…catch Capture processing .

    //async function  + await expression : An asynchronous function 
    async function fn() {
    
      //await  Back to promise Success value 
      let result = await new Promise((resolve, reject) => {
    
      resolve(' success ')
    });
      console.log(result); // success 
    }
    fn();

One await Example :

let a = 0;
let b = async () => {
    
  a = a + (await 10);
  console.log('2', a);
};
b();
a++;
console.log('1', a);

// First, the output  ‘1’, 1
// At output  ‘2’, 10
  • First of all, the function b Execute first , In carrying out the await 10 Previous variable a still 0, because await Internally implemented generator ,generator Will keep things in the stack , So at this point a = 0 Preserved
  • because await Is asynchronous operation , Later expressions do not return Promise Words , Will be packaged as Promise.reslove( Return value ), Then it will execute the synchronization code outside the function
  • Synchronization code a++ And printing a After execution, start executing asynchronous code , Use the saved value , Now a = 0 + 10

The above explanation refers to await Internally implemented generator, Actually await Namely generator add Promise The grammar sugar of , And the internal implementation of automatic execution generator.

Generator How it's used and how it's changed at each stage ?(3 star )

answer :

  • First, the generator is a function , Used to return iterators
  • Not immediately after calling the generator , It controls the step-by-step execution of the generator through the returned iterator
  • By calling the iterator's next Method to request values one by one , The returned object has two properties , One is value, That's the value ; The other is done, It's a boolean type ,done by true The generator function is finished , There is no value to return ,
  • done by true And then continue to call the iterator next Method , The return value of value by undefined

State change :

  • Whenever the execution reaches yield When attributes , Will return an object
  • At this point, the generator is in a non blocking pending state
  • Calling iterator's next Method time , The generator changes from pending state to executing state , Continue with the last execution position execution
  • Until the next time yield In turn, cycle
  • Until the code doesn't yield 了 , Will return a result object done by true,value by undefined

The advantages and disadvantages of asynchronous implementation methods and their respective methods (4 star )

Mode one : Callback function (callback): Pass a function as an argument to another function , When that function is executed , Then execute the function passed in , This process is called callback

Back to hell : Callback functions are nested layer by layer , Layer upon layer dependency, low code readability 、 Inconvenient for later maintenance

advantage : Solved the problem of synchronization ( As long as one task takes a long time , The next task has to wait in line , Will delay the execution of the whole procedure .)

shortcoming : Back to hell , Only one callback function can be specified per task , You can't return.

Mode two : Promise

Promise Just to solve it callback The problem of .

Promise Implementation of the chain call , That is to say, every time then All of them are brand new Promise, If we were then in return ,return The result will be Promise.resolve() packing

advantage : Solved the problem of callback to hell

shortcoming : Can't cancel Promise , The error thrown internally needs to be caught through the callback function

Mode three : generator Gnenrator

Generator Is a solution to asynchronous programming , Solve callback hell

Mode 4 :async/await

advantage : Clear code , Don't look like Promise Write a lot of then chain , Dealt with the problem of callback to hell

shortcoming :await Transform asynchronous code into synchronous code , If multiple asynchronous operations are used without dependency await Will lead to performance degradation .

The way to solve the hell of asynchronous callback (3 star )

Promise、generator、asynac/await

forEach、for in、for of The difference between (5 star )

forEach Traversal array , But you can't use break、continue and return sentence

for...in Is used to loop with a string key The object of the method . It's actually a loop ”enumerable“( enumerable ) Designed for objects

for...of Array objects can be traversed , Traversing an object requires passing and Object.keys()

for in What circulates is key,for of What circulates is value

Enumerable properties It refers to those internal “ enumerable ” Flag set to true Properties of .

For properties initialized by direct assignment and properties , The default value of this indicator is true.

Js The prototype properties of the basic data type cannot be enumerated , adopt Object.defineProperty0 Method specification enumeralbe by false The properties of cannot be enumerated .

Set、Map、WeakSet and WeakMap The difference between ?(3 star )

Set aggregate : It's like an array , But the values of members are unique . Array weight removal

Map aggregate : Similar to the object , It's also a set of key value pairs , but ’ key ’ Not limited to strings , Various types of values ( Including objects ) It can also be used as a key .

Application scenarios Set For data reorganization ,Map For data storage

Set

  1. Members cannot be duplicated
  2. Only the key value has no key name , It's like an array
  3. Traversable , There are methods add, delete,has

Map:

  1. It is essentially a set of key value pairs , Like a collection
  2. Traversable , It can be converted with various data formats

WeakSet Structure and Set similar , It's also a set of values that don't repeat . But with Set There are several differences :

  • WeakSet Members of It can only be the object , It can't be any other type of value
  • WeakSet The objects in are all weak references
    • If no other object references that object , Then the garbage collection mechanism will automatically reclaim the memory occupied by the object
    • WeakSet Suitable for temporary storage of a group of objects , And storing information bound to objects . As long as these objects disappear outside , It's in WeakSet The references in it will disappear automatically .

WeakMap It applies to the data you want to add to the object , I don't want to interfere with the garbage collection mechanism

A typical application scene yes , On the web DOM Add data to element , You can use WeakMap structure . When it's time to DOM Elements are removed , The corresponding WeakMap The records are automatically removed .

Deconstruct assignment (3 star )

ES6 Allows you to extract values from arrays , According to the corresponding position , Assign a value to a variable . Objects can also be deconstructed
Residual parameter syntax allows us to represent an indefinite number of parameters as an array .

//...args ... Indicates that the remaining parameters are accepted 
function sum(first, ...args) {
    
  console.log(first);//10
  console.log(args);//[20,30]
}
sum(10, 20, 30);

An array of deconstruction

let [a, b, c] = [1, 2, 3]   //a=1, b=2, c=3
let [d, [e], f] = [1, [2], 3]    // Nested array deconstruction  d=1, e=2, f=3
let [g, ...h] = [1, 2, 3]   // Array splitting  g=1, h=[2, 3]
let [i,,j] = [1, 2, 3]   // Discontinuous deconstruction  i=1, j=3
let [k,l] = [1, 2, 3]   // Incomplete deconstruction  k=1, l=2

Object to deconstruct

let {
    a, b} = {
    a: 'aaaa', b: 'bbbb'}      //a='aaaa' b='bbbb'
let obj = {
    d: 'aaaa', e: {
    f: 'bbbb'}}
let {
    d, e:{
    f}} = obj    // Nested deconstruction  d='aaaa' f='bbbb'
let g;
(g = {
    g: 'aaaa'})   // Deconstruct... With declared variables  g='aaaa'
let [h, i, j, k] = 'nice'    // String deconstruction  h='n' i='i' j='c' k='e'

Event agent / Event delegation (3 star )

It refers to not setting listening on the trigger target of the event , Instead, set in its parent element , Through the bubbling mechanism , The parent element can listen to the triggering of events on the child element .

Why use modularity ?

There are several ways to achieve modularity , What are the characteristics of each ?(3 star )

  • modularization It means that a large program file , Split into many small files , Then combine the small files .

    A module is a set of methods to implement a specific function

    advantage :1. Prevent naming conflicts ;2. Code reuse ;3. High maintenance ;

    Realize modularization

    • AMD
    • CMD
    • CommonJS modular
    • ES6 modular

exports and module.exports What's the difference? ?(3 star )

  • The export method is different
    • exports.xxx='xxx'
    • module.export = {}
  • exports yes module.exports References to , Two points to one address , and require All you can see is module.exports

Module loading scheme comparison :CommonJS modular And ES6 modular (3 star )

CommonJS modular , It passes through require To introduce modules , adopt module.exports Define the output interface of the module . This module loading scheme is a server-side solution , It introduces modules in a synchronous way , Because on the server side, the files are stored on the local disk , So reading is very fast , So there's no problem loading synchronously .

ES6 modular Use import and export To import and export modules in the form of .

difference :

  • CommonJS The output of the module is a copy of the value ,ES6 The module outputs a reference to a value .CommonJS The output of the module is a copy of the value , Changes within the module do not affect this value .ES6 Modules are dynamic references , And it doesn't cache values , The variables in a module are bound to the module they are in .

  • CommonJS Modules are run time loaded ,ES6 Module is a compile time output interface An external interface is just a static definition , It will be generated during the static parsing phase of the code .CommonJS Modules are objects , That is to load the whole module before input , Generate an object , Then read the method from the object , This load is called “ Load at run time ”. and ES6 Module is not an object , Its external interface is just a static definition , It will be generated during the static parsing phase of the code .

Extension operator

Extension operators can convert an array or object into a comma separated sequence of parameters .

let ary = [1, 2, 3];
...ary //1,2,3
console.log(...ary);//1 2 3

Extension operators can be applied to merge arrays .

let ary1 = [1, 2, 3];
let ary2 = [4, 5, 6];
ary1.push(...ary2);
console.log(ary1);//[ 1, 2, 3, 4, 5, 6 ]

Cross domain

The same-origin policy

If two pages ( Interface ) The agreement 、 domain name 、 All port numbers are the same , We think they are homologous
The same origin policy is a security restriction of the browser , It stops the difference 【 Domain 】 Data interaction between

What are the ways to cross domain ? What are their characteristics ? (5 star )

Cross domain A document or script in one domain tries to request resources in another domain
The same-origin policy yes browser Restrictive policies for security ( Therefore, the server does not involve cross domain ), The homology policy is given by the browser Ajax Technical limitations , Can't send... To a non homologous address Ajax request , There is no homology policy restriction on the server side . Browser requests must follow the same origin policy , It's the same domain name 、 Same port 、 Same agreement

As the agreements 、 subdomain 、 The main domain name 、 Any one of the port Numbers is different , They all count as different domains . Cross-domain is not a request that cannot be sent , The request can be sent , The server receives the request and returns the result as normal , Only the result was blocked by the browser .

JSONP

  • JSONP principle : It is through script The tag obtains the data sent from the back-end interface through js Realization , however jsonp Can only solve get request , That's one of its drawbacks . And it's not safe json hijacked : Attackers can construct malicious JSONP Call page , Induce the attacker to access to intercept user sensitive information

  • JSONP Can only get request

  • Source code :

        function addScriptTag(src) {
          
          var script = document.createElement("script")
          script.setAttribute('type','text/javascript')
          script.src = src
          document.appendChild(script)
        }
    
        //  Callback function 
        function endFn(res) {
          
          console.log(res.message);
        }
        //  We'll talk it over , If the back end transmits data , return `endFn({messag:'hello'})`
    

CORS

CORS( Cross-domain resource sharing ) principle : It allows the browser to cross to the source server , Request , To overcome AJAX A restriction that can only be used with the same origin . Realization principle : When the server returns a response, set a cross domain permission for the response header header, hold Access-Control-Allow-Origin Specify the domain name that can obtain data
CORS There are two types of requests : A simple request It's not a simple request .
A simple request , The browser adds a... In the request header Origin Field is sent directly CORS request
It's not a simple request , Will be before formal correspondence , Add a HTTP Query request , The browser asks the server first , Only when you get a positive reply from the server , The browser will send a formal request , Otherwise, it will be wrong .

The browser asks the server first , Whether the domain name of the current web page is in the server's license list , And what can be used HTTP Verb and header fields . Only a positive response , Browser will send out official XMLHttpRequest request , Otherwise, it will be wrong .
nginx Reverse proxy cross domain
hold Client and nginx The reverse proxy server is placed on the same port , In this way, there will be no homology restriction , and nginx Simulate a virtual server , There is no cross domain between servers , You can put the client http The request is forwarded to another or some servers , So as to easily realize cross domain access

  • When sending data , client ->nginx-> Server side
  • When returning data , Server side ->nginx-> client
    Forward agency Is a proxy server between the client and the target server , In order to get content from the target server , Send a request to the proxy server , Then the proxy server forwards the request to the target server and returns the obtained content to the client
    For the client , Reverse proxy It's like the target server . Client sends request to reverse agent , Then the reverse agent determines where the request is going , And forward the request content to the client , To make it look like him , The client is not aware of the services behind the reverse proxy , Just think of the reverse proxy as a real server .

We often say agency, that is, forward agency , The process of forward agency , It hides the real request client , The server does not know who the real client is , The services requested by clients are replaced by proxy servers to request .
The reverse proxy hides the real server , When we ask for a website , There may be thousands of servers behind us , But which one is it , We don't know , I don't need to know , We just need to know who the reverse proxy server is , The reverse proxy server will help us forward the request to the real server . Reverse proxy is generally used to achieve load balancing ( Try not to say ).

DOM

DOM Several ways and differences of binding events (3 star )

  • element.onclick, Elements + Event type

Bind multiple similar events to the same element , What is written later will overwrite the previous event

  • addEventListener Method
    btn.addEventListener(type, handle, true) The three parameters are event type , Event handler , The stage of implementation ;
    The third parameter has two values ,true and false,false The default value is , The event bubble phase executes ,true The event capture phase executes

Bind multiple similar events to the same element , No overwriting will occur , The bound events will be executed in sequence

DOM Flow of events (5 star )

 Insert picture description here

getElementById querySelector querySelectorAll Get elements

Both event flows trigger DOM All objects of , from window Object start , Also in the window End of object .

DOM The standard specifies that the event flow includes three stages :

  • Event capture phase
  • At the target stage
  • Event bubbling stage

Both capture and bubble phase event flows trigger DOM All objects of , from window Object start , Also in the window End of object .

What's the difference between event capture and event bubbling ?(5 star )

  • Event capture

    • Top to bottom ( Ancestors to sons ) perform
    • stay addEventListener The third property in is set to true
  • Event Bubbling Event agent / Event delegation

    • From bottom to top ( From son to ancestor ) perform
    • stay addEventListener The third property in is set to false( Default )

miscellaneous

this What kinds of situations are there in the direction of ?(5 star )

this Represents the object associated with the function call , It is usually called execution context .

  1. Call directly as a function , Non strict mode ,this Point to window, In strict mode ,this Point to undefined;
  2. Call as a method of an object ,this Usually points to the object being called .
  3. apply、call、bind Can be bound this The direction of .
  4. In the constructor ,this Points to the newly created object
  5. There is no separate arrow function this value ,this Determine when the arrow function is created , Arrowhead function this Point to parent : First, find... From its parent scope , If the parent scope is still an arrow function , Look up again , Until I find this The direction of .

What is anti shake ? What is throttling ? Writing a (5 star )

Anti shake throttling is a method to control the trigger frequency of events

  • Shake proof : An event n Seconds later , If in n It's repeatedly triggered in seconds , Then the time will be counted again ,
    The text editor saves in real time , Save one second after no change operation
    Frequent operation and cancellation of praise , Therefore, we need to get the result of the last operation and send it to the server
    Sign in 、 Send text messages and other buttons to prevent users from clicking too fast , So many requests were sent , Need anti shake

  • throttle : An event n Only once per second , If in n Repeat the trigger in seconds , Only once
    Mouse click to trigger , Trigger only once per unit time ( Click many times per unit time , But only once )
    Association of search keywords : Every period of time triggers , It can also be made into the last execution in the anti shake unit time , Only triggered last time

  // Anti shake function   Focus on clearing  clearTimeout(timer)
  // During the timer , When there is a new operation , Empty the old timer , Reset the new timer 
function debounce(fn, time)  {
    
// Declare a timer first 
	let timer
	return function() {
    
	// If the timer is present, clear 
		if(timer) clearTimeout(timer)
		// Otherwise reset the new timer 
		timer = setTimeout(() => {
    
			fn.call(this)
		}, time)
	}
}



  //  throttle   Focus on the switch lock  timer=null  The timer is used to ensure the number of events triggered in the interval 
// Pass in two values , One is the method to be executed , One is the execution cycle 
function throttle(fn,time) {
    
	// First declare a timer 
	let timer
	// Return a method ( Closure )
	return function() {
    
		// If the timer exists, do not execute 
		if(timer) return
		// If the timer does not exist, execute 
		// Set a timer for self cleaning for a certain period of time 
		timer = setTimeout(() => {
    
			// this this At that time, it will become the element calling this method 
		    fn.call(this)
			timer = null
		},time)
	}
}

The principle of function coriolisation (5 star )

// The function is coriolized , The technique of decomposing a function into multiple parameters is to accept a single parameter , Until the received parameters meet the original required quantity , To execute the original function 
// Simply save the parameters with closures , When the number of parameters is enough to execute the function , Start executing functions 
// Reduce code duplication , Improve the applicability of the code 
const curry = (fn, ...args) => fn.length <= args.length //  Judge that the number of parameters is enough to execute the function 
  	? fn(...args) //  Arguments are sufficient to execute the function 
    : curry.bind(null, fn, ...args) //  If the parameters are not enough, the existing parameters will be returned , Use bind Combined with the idea of closure, return a temporary function 
        //fn(this,1,2)  change fn Medium this,fn Not implemented   Wait for the event to trigger 
//  test 
function sum (a, b, c) {
     return a + b + c }
let currySum = curry(sum)

console.log( currySum(1, 2, 3) ) // 6// With  currySum(1, 2, 3) For example , You can save... With a variable curry(1, 2), Then just pass in the third parameter at a time , It is equivalent to that the first two parameters are given 

js Common design patterns (5 star )

A design pattern is a set that is used repeatedly , Most people know that , classified , Summary of code design experience .

  • The singleton pattern 、 Factory mode 、 The proxy pattern
    The singleton pattern
    Concept : The same constructor , Generate a unique instance , Prevent duplicate instantiations
    advantage : Save memory space , Improve the efficiency of program execution

1. There is only one example .2. Global access .3. Save memory

var Single = (function () {
    
      var instance = null
      function Single(name) {
    
        this.name = name
      }
      return function (name) {
    
        if (!instance) {
    
          instance = new Single()
        }
        return instance
      }
    })()

    var oA = new Single('hi')
    var oB = new Single('hello')
    console.log(oA);
    console.log(oB);
    console.log(oB === oA);

Factory mode

Instead of new Create an object , And this object is made like a factory , Batch create instance objects with the same properties ( Point to different )

 function Animal(o) {
    
      var instance = new Object()
      instance.name = o.name
      instance.age = o.age
      instance.getAnimal = function () {
    
        return "name:" + instance.name + " age:" + instance.age
      }
      return instance
    }

    var cat = Animal({
    name:"cat", age:3})
    console.log(cat);

The proxy pattern
In some cases , One object is not suitable or cannot directly reference another , The proxy object can act as an intermediary between two objects .

JS Ways to optimize performance (5 star )

  • Garbage collection
  • Objects in closures are cleared
  • Anti shake throttling
  • Batch loading (setInterval, load 10000 Nodes )
  • Event delegation
  • script In the tag defer and async
  • CDN

Preloading and lazy loading of pictures

  • Preloading : Load pictures in advance , You can render directly from the local cache when you need to view
  • Lazy loading : Delay loading , That is, load the object when it needs to be used
    The main purpose of lazy loading is to optimize the front end of the server , Reduce requests
 Lazy loading principle img Medium src attribute , Cut the data according to the visual area 

The essence of the two technologies : The behavior of the two is opposite , One is to load ahead of time , One is slow or even does not load . Preloading increases the pressure on the front end of the server , Lazy loading can relieve the pressure on the server .

cookie、session、token、jwt The difference between

answer :
Cookie because HTTP Protocol is stateless , The business on the server side must be stateful .Cookie Is produced to store web Status information in , For the convenience of the server . cookie Store on client ,cookie It's not cross domain

session Is based on cookie Realized Is another mechanism for recording the state of the server and client sessions

token yes Access resource interface (API) Resource credentials required for
Token and cookie、session The difference between

  • cookie Store... In the client , Easy to forge , Not as good as session Security
  • session It will consume a lot of server resources ,cookie In every time HTTP The request will be accompanied by , Impact on network performance
  • because session Stored on the server side , When there are a large number of users, there will be some scalability problems .token Store on client , There is no such problem
  • Cookie Cross domain access is not allowed , token Cross domain
  • Send on request token Can prevent CSRF( Cross-site request forgery ),cookie must not

authentication ( authentication ) It means to verify whether the user has the right to access the system , Is to verify the identity of the current user , prove “ You are yourself ”, Such as user name and password login , When your information matches the database, you will log in successfully

to grant authorization It is the permission granted by the user to the third-party application to access some resources of the user

voucher It is the premise of realizing authentication and authorization , Need a medium ( certificate ) To mark the identity of the visitors

JWT

  • JSON Web Token( abbreviation JWT) It's the most popular at the moment Cross domain authentication Solution . It's a kind of Authentication and authorization mechanism .

  • JWT The declaration of is generally used to pass the authenticated user identity information between the identity provider and the service provider , To get resources from the resource server . For example, it's used in user login .

  • JWT It's made up of three parts : The first part is what we call the head (header), The second part is called load (payload, Similar to what is carried on an aircraft ), The third part is visa (signature).

    jwt There are three parts :A.B.C

    A:Header,{“type”:“JWT”,“alg”:“HS256”} Fix

    B:playload, Store information , such as , user id, Expiration time, etc , Can be decrypted , Can't store sensitive information

    C: visa ,A and B Add the secret key Encrypted , As long as the secret key is not lost , It can be considered safe .

    jwt verification , The main thing is verification C part Is it legal

    Use : stay HTTP Asking for header information Authorization In the field , Use Bearer Mode add JWT, Authorized to carry token Information

    • The protection route of the server will check the request header Authorization Medium JWT Information , If the legitimate , Then allow the user's behavior
    • because JWT It's self-contained ( Some session information is included internally ), So it reduces the need to query the database
    • because JWT Not used Cookie Of , So you can use any domain name to provide your API Services without worrying about cross domain resource sharing (CORS)
    • Because the user's state is no longer stored in the server's memory , So this is a stateless authentication mechanism

cookie、session The difference between

  • cookie Stored on the client ,session The storage lies in the server . session Is based on cookie Realized ,session Store on the server side
  • cookie Store... In the client , Easy to forge , Not as good as session Security
  • session It will consume a lot of server resources ,cookie In every time HTTP The request will be accompanied by , Impact on network performance

Token and JWT The difference between

identical :

  • Are tokens to access resources
  • Can record the user's information
  • It is to make the server stateless
  • It is only after the verification is successful , Only the client can access the protected resources on the server

difference :

  • Token: The server verifies that the client sent Token when , You also need to query the database for user information , And then verify Token Whether it works .
  • JWT: take Token and Payload Encrypted and stored in the client , The server only needs to use key decryption for verification ( Verification is also JWT Self realized ) that will do , No need to query or reduce the number of query databases , because JWT Self contained user information and encrypted data .

cookie,sessionStorage and localStorage The difference between ?

  • In the same browser, the life cycle is different

Cookie Life cycle : Default is disable when browser is closed , However, you can also set the expiration time

SessionStorage Life cycle : Only in the current session ( window ) Effective under , Cleared after closing the window or browser , Can't set expiration time

LocalStorage Life cycle : Unless removed , Otherwise permanent

  • Different capacities

Cookie Capacity limit : size (4KB about ) And the number (20~50)

SessionStorage and LocalStorage Capacity limit : size (5M about )

  • Network requests are different

Cookie Network request : Every time I carry it in HTTP Request header , If you use cookie Saving too much data can cause performance problems

SessionStorage and LocalStorage Network request : Save in browser only , Does not participate in communication with the server

ajax

What is? ajax? The creation process

ajax Is a method of asynchronous communication , Get data from the server , Achieve the effect of partially refreshing the page .Ajax It is equivalent to the agent that the client sends the request and receives the response , In order to achieve without affecting the user browsing the page , Locally update page data , To improve the user experience .
The process :
establish XMLHttpRequest object ;
call open Method passes in three parameters Request mode (GET/POST)、url、 Synchronous asynchronous (true/false);
monitor onreadystatechange event , When readystate be equal to 4 When to return to responseText;
call send Method pass parameter .

The difference between synchronous and asynchronous

Sync :
Browser access server request , Users can see the page refresh , Resend request , Wait for the request to finish , page refresh , New content appears , Users see new content , Proceed to the next step

asynchronous :
Browser access server request , Normal operation of users , Browser backend requests . Wait for the request to finish , The page does not refresh , New content will appear , Users see new content

ajax and axios The difference between (5 star )

ajax Technology to achieve the local data refresh page , It is the agent for the client to send requests and receive responses ,axios It's through promise Realize to ajax A kind of encapsulation of Technology , install axios Dependency is used to initiate ajax request

ajax: It's about MVC Programming for , Not in line with the current front end MVVM The wave of
axios: from node.js establish http request Support Promise API Client support prevents CSRF Provides some interfaces for concurrent requests

ajax Advantages and disadvantages of

ajax The advantages of

1、 No refresh update data ( Maintain communication with the server without refreshing the entire page )

2、 Asynchronous communication with the server ( Communicate with the server asynchronously , Do not interrupt the user's operation )

3、 Front end and back end load balancing ( Leave some back-end work to the front-end , Reduce the burden of server and width )

4、 Interface and application are separated (ajax Separate the interface from the application, that is, separate the data from the presentation )

ajax The shortcomings of

1、ajax Browser not supported back Button

2、 safety problem Aajax Exposed the details of the interaction with the server

3、 Weak support for search engines

4、 Destroyed Back And History The normal behavior of the back button and other browser mechanisms

js Built-in objects String Array Math Date Common methods

String String common methods :

 str.length: Length of string 
 str.charAt( Indexes ), The return value is the string that specifies the index location , Out of index , The result is an empty string 
 str.concat( character string 1, character string 2,...); The new string after splicing is returned 
 str.indexOf( String to find , Index starting from a certain location ); It returns the index value of this string , If you don't find it, go back -1
 str.lastIndexOf( String to find ); Look back and forth , But indexing is still left to right , Return if not found -1
 str.replace( The original string , New string ): Used to replace strings 
 str.slice( Index started , End index );  Extract a fragment of a string , And return the extracted part in the new string , From the index 5 The location of the start extraction , To index as 10 The previous end of , No, 10, And return the extracted string 
 str.split() Split a string into an array of strings 
 "hello".split("")	// You can go back to  ["h", "e", "l", "l", "o"]
 str.substr( Starting position , Number ); What is returned is the new string after truncation 
 str.substring( Index started , End index ), Return the truncated string , String without ending index 
 str.toLocaleLowerCase(); Turn lowercase 
 str.toLowerCase(); Turn lowercase 
 str.toLocaleUpperCase() Turn capitalization 
 str.toUpperCase(); Turn capitalization 
 str.trim(); Kill the spaces at both ends of the string 
 str.fromCharCode( Numerical value , It can be multiple parameters ), The return is ASCII The value of the code 

Array Array common methods :

Array.isArray/instanceof/typeof/Object.prototype.toString.call: Determine whether it is an array     
map( function ):  Traversal array , Returns a new array of callback return values 
forEach( function ):  Traversing an array is equivalent to for loop , unable break, It can be used try/catch in throw new Error To stop 
filter( function ):  Filter , Returns the qualified elements in the array , Make up a new array 
some( function ):  Returns a Boolean type , One item that meets the conditions returns true, The whole is true
every( function ):  Returns a Boolean type , There is a return false, The whole is false
join( character string ):  Generate string by specifying connector 
push / pop:  Push and pop end , Change the original array ,  After pushing the length of the array and returning the new value 
unshift / shift:  Head in and out , Change the original array , After pushing the length of the array and returning the new value 
sort/ reverse:  Sort ( It could be unstable , Please write MDN The fixed code in ) And inversion , Change the original array 
concat:  Linked array , Does not affect the original array ,  Shallow copy 
slice(start Index started , end End index ):  Returns the new array after truncation , Do not change the original array 
splice(start Starting position , number Number of deletions ,  Replacement value ):  It is generally used to delete elements in an array , Returns an array of deleted elements , Change the original array 
indexOf / lastIndexOf( Value to find value,  Index starting from a certain location fromIndex):  Before and after / Find array items from back to front , The index is returned , If not, it is -1
reduce(function(prev,cur,index,arr){
    ...}, init);
reduce()  Method to receive a function as an accumulator , Every value in the array ( From left to right ) Start to shrink , The final calculation is a value .
prev  It's necessary . The accumulator accumulates the return value of the callback ;  Represents the return value when the callback was last called , Or the initial value  init;
cur  It's necessary . Represents the array element currently being processed ;
index  Optional . Represents the index of the array element currently being processed , If provided  init  value , The starting index is - 0, Otherwise, the starting index is 1;
arr  Optional . Represents the original array ;
init  Optional . Represents the initial value .

Math Common methods :

Math.ceil(x)--- Rounding up  
Math.floor(x)--- Rounding down  
Math.Pi---- The value of pi  Math.Max(num1,num2,...)--- The maximum of a set of numbers  
Math.Min(num1,num2,...)--- The minimum of a set of numbers   
Math.abs(x)---- The absolute value  
Math.random()--- Random numbers ( Range 0~1)  
Math.sqrt(x)---- Square root  
Math.pow(x,y)---- How many powers of a number    x^y

Date Common methods :

 var dt=new Date(); console.log(dt);    Current time --- Current server  
 var dt=new Date("2019-01-11");  // Incoming time    
 dt.getFullYear();// year   
 dt.getMonth();// month --- from 0 Start    
 dt.getDate();// Japan     
 dt.getHours();// Hours   
 dt.getMinutes();// minute    
 dt.getSeconds();// second    
 dt.getDay();// week --- from   0   Sunday    Start   
 dt.toDateString();// date     
 dt.toLocaleDateString();// date   
 dt.toTimeString();// Time    
 dt.toLocaleTimeString();// Time   
 dt.valueOf();// millisecond 

miscellaneous

stay js in , Add strings and numbers , Will turn numbers into strings and add them up ,‘5’+3=“53”
Subtracting a string from a number , Will turn the string into a number and subtract ,‘5’-3=2
Common data structures are arrays , queue , Pile up , Stack , Trees , chart , Hash table , Chain list, etc

Let's talk about token The process of realizing single point login , What's the idea ( First the token Stored in localstorage in , In the use of cross domain to solve sub domain name sharing token)

vuex effect ,vuex and localstorage difference , Essential difference , The drive is different ( One is memory storage , One is that the browser permanently stores , vuex Apply to shared data between components ,local More for passing between pages

版权声明
本文为[Front end more]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230550117801.html