This is from the beginning of my JS learning to ES6 records in the notes refined out of their own feel more important knowledge points. I hope it’s a little bit helpful and if you think it’s ok, just click on it!!!! Hey hey

1. Classification and judgment of data types

  1. Basic data types

    Number typeof() ==number String typeof() ==string Boolean typeof() == boolean undefind typeof() == undefind null typeof() == object

  2. Reference data type

    Object Typeof () == Object Array Typeof () == Object Function Typeof () == Function instance of: Determines whether a variable belongs to a data type

    Null ==undefined /true

    Null ===undefined/false

2. The relationship among memory, data and variables

Memory is a container for storing different kinds of data and variables are the identifiers of memory through which we can manipulate data in memory and we can divide it into stack memory and heap memory

  1. Stack memory: The address that holds the base data type and the reference data type (the address refers to the data in the heap memory)

  2. Heap memory: Holds data referencing data types

    Assignment operations for basic data types make a complete copy of the data in stack memory without affecting each other. Assignment operations that refer to data types assign values to addresses in stack memory. They refer to the same memory space and affect each other.

3. Implement a bubble sort

Var arr=[3,2,1] var temp; var arr=[3,2,1] var temp; var arr=[3,2,1] var temp; var arr=[3,2,1] var temp; for(var i=0; i<=arr.length-1; Var j=0; var j=0; j<arr.length-1-i; J++) {/ / inner loop tube exchange times on a visit to the if (arr [j] < arr [m + 1]) {temp = arr [j]; arr[j]=arr[j+1]; arr[j+1]=temp; }}}Copy the code

4.JS common built-in objects and their common apis

  1. Math.floor()// round down math.ceil ()// round up math.abs ()// absolute value math.max ()/min()// take maximum and minimum values
  2. Date getFullYear()// getMonth() of the current year // getDate() of the current month (0-11)// getDate() of the current day getHours()// getMinutes() of the current minute GetSeconds ()// Gets the current second
  3. Unshift (); unshift(); shift(); unshift(); shift(); unshift(); Reverse ()// reverse array, sort()// array sort, indexOf()// find the first indexOf a given element in array, 1 join(‘ delimiter ‘)// Convert array elements to concatenated strings with the given delimiter concat()// Concatenate multiple arrays, does not affect the original array slice(start, end)// Array truncation, returns the truncated array splice(start, num, NewVal)// Can implement interception, replacement, insert, etc
  4. CharAt (index)// Returns the character at the specified position in the String

5. Implement the array to duplicate the method

  1. ES6 most commonly uses Set data structures for deduplication (AN Sst data structure is an ordered non-repeating data structure object)

    Return array. from(new Set(arr))} function unique1(arr){// array. from converts an arraylike object or a traversable object into a real Array.Copy the code
  2. ES5 most commonly uses double for loops to reuse splice for weight removal

Function unique2(arr){for(let I = 0; i < arr.length ; i++){ for(let j = i+1 ; j < arr.length ; j++){ if(arr[i] == arr[j]){ arr.splice(j,1) j-- } } } return arr }Copy the code
  1. Use indexOf to remove weights

    function unique3(arr){
        let newArr = []
        for(var i = 0 ; i < arr.length ; i++){
            if(newArr.indexOf(arr[i]) === -1){
                newArr.push(arr[i])
            }
        }
        return newArr
    }
    Copy the code
  2. Filter is used to remove weight

function unique4(arr){
    return arr.filter((item,index,arr)=>arr.indexOf(item) === index)
}
Copy the code

6. Common API for DOM node operation

  1. Create a node

    Document.write ()// Write the content directly to the content stream of the page. The page is fully redrawn when the document stream is completed.

  2. Insert node appendChild() insertBefore()

  3. Remove node node.removechild ()

  4. Modify element attributes: SRC /href/title Modify common element contents: innerHTML/innerText Modify form elements: value/type/disabled Modify element styles: style/className

  5. Access to the DOM node (not recommended) provided by the getElementById/getElementByTagName H5 provides new way: querySelector/querySelectorAll (get) is a pseudo array using the node to get: Access to the parent element: parentNode for child elements: children takes sibling elements: previousElementSibling/nextElementSibling

  6. Custom attribute operation setAttribute getAttribute

    removeAttribute

7. Event delegation

Definition: Sets a listener for a child node on its parent node, and then affects each node with bubbling of events

For example, if you register a click event with UL and use the target of the event object to find the currently clicked Li, the event will bubble up to UL and trigger the corresponding listener

Advantages: Provides performance by manipulating dom once in

8. Local storage

** Only string data can be stored

  1. SessionStorage (life cycle is browser window, The same window data can be Shared) sessionstorage. SetItem (key, val) sessionstorage. The getItem (key, val) sessionstorage. RemoveItem (key)
  2. Sessionstorage. clear localStorage(life cycle is permanent, SetItem (key,val) localstorage.getitem (key,val) localstorage.removeItem (key) localStorage.removeItem(key) localStorage.clear

9.JS recycling mechanism

First, the garbage collection mechanism is a circular mechanism, and js is scanned periodically

  1. Count Clear (IE and lower Versions of Chrome)

    If the pointer points to 0, it indicates that the address will be cleared

  2. Mark clear

    When a variable is detected in the code execution environment, an entry flag is added to the variable, and a factory flag is added after the code execution is complete. The ones with the factory mark are the ones to be cleared.

10. Anti-shake and throttle

  1. Function debounce

    1. Concept: An event is reset n seconds after it is triggered, and if it is triggered again within n seconds

    2. Application scenario: multiple clicks of the button on the price increase form, request for images and other resources from the server, and further processing of the request results

    3. Conclusion: Function stabilization is suitable for multiple events with one response

      Function buffeting means that js methods run only once in a certain amount of time. If the previous trigger does not end, the subsequent trigger will be calculated by the new interval of the previous trigger.

    4. Code implementation (closure)

      let timeout = null; function debounce(fn, wait) { return (args) => { if (timeout ! == null) {clearTimeout(timeout)} timeout = setTimeout(() => fn(args), wait)}Copy the code
  2. Function throttling

    1. A callback that can trigger only one event per unit of time

    2. Application scenarios: DOM element drag, search box linkage response prompt function, continuous trigger of the scroll bar

    3. Summary: Function throttling is suitable for a large number of events to be fired evenly over time

      Function throttling means that js methods run only once in a certain amount of time. The last one didn’t end, the last one won’t run.

    4. Code implementation

      let _lastTime = null; function throttle(fn, gapTime) { return (args) => { let _nowTime = + new Date(); if (_nowTime - _lastTime > gapTime || ! _lastTime){ fn(args); _lastTime = _nowTime}}}// The function is triggered only when the interval between two functions is shorter than the specified intervalCopy the code

11. The new executive function this points to

  1. Four things that happen when new is executed

    1. Create an empty object
    2. This refers to the empty object
    3. Execute the code inside the constructor to add properties and methods to the object
    4. Return a new object
  2. The function this points to

    1 This is also a variable by default, but it is not specified when the function bit is used

    The this of the 2 function is determined not when it is defined, but when it is called

    3 self call of function: this–>window

    4 when new: this–> currently generated instance object

    5 obj.test():this–>obj

12. Prototypes and prototype chains

In order to abstract out a class of things and make the same class of things have the same attributes and methods, JS takes the prototype chain as the main way to achieve inheritance. In terms of data structure, a prototype chain is actually a linked list. The instance has a pointer to the prototype, and the prototype contains a pointer to the constructor

  1. Display the prototype object

    Each constructor has a prototype property, and prototype is an object.

    What it does: Share methods. In general, our public properties are defined in constructors, and our public methods are put in stereotypes. Because if you put a method inside a constructor, each instance you create opens up a chunk of memory to hold the method. If you define a method on the constructor’s prototype, its instances can all be called through the prototype chain.

  2. Object prototype — Proto — (Implicit prototype object)

    Each object has an object prototype that points to the constructor’s prototype, so proto and Prototype are equivalent

    Purpose: To provide a direction, a route for the object search mechanism.

  3. Relationships between constructors, instances, and prototype objects

  4. Prototype chain

    function Foo () {}

    var f1 = new Foo()

    var f2 = new Foo()

    var o1 = {}

    var o2 = {}

5. Js member lookup mechanism

  1. When you access an object’s property or method, you first look up whether the object itself has the property
  2. If not, look for the prototype object proto points to.
  3. If not, find the prototype of the prototype Object.
  4. And so on until Object is null
  5. The meaning of proto object prototype is to provide a direction, a line for the object member search mechanism

13. Execution context and execution context stack

  1. Variable promotion and function promotion (pre-analysis)

    Variable promotion: Access to the variable (undefined) before the variable definition statement.

    Function promotion: Executes the function before the function definition statement

    Function promotion takes precedence over variable promotion

  2. understand

    Execution context: An object automatically created by the JS engine that contains all variable properties in the corresponding scope

    Execution context stack: Used to manage the multiple execution contexts generated

  3. Classification and life cycle

    Global (window) : Generated before global code is ready to execute and dies when the page is refreshed/closed

    Function: generated when a function is called, dead when the function is finished

  4. Contains properties

    Global:

    Global variable defined with var ==>undefined

    Function declared with function ===>function

    this ===>window

    Function:

    Local variables defined with var ==>undefined

    Function declared with function ===>function

    This ===> The object on which the function is called, or window if not specified

    Parameter ===> corresponds to the value of the argument

    Arguments ===> pseudo-array of argument lists

  5. Perform context creation and initialization

    The js engine creates and enters the execution environment immediately before the JS code executes

    Create an empty object –> execute context object

    3 collect variables (var keyword), functions (function), parameters of functions,

    4 Determine the direction of this

    5 Create a scope chain

    Execution context stack: Used to hold execution context objects (features of pushdown: FIFo, LIFO)

14. Scope and scope chains

  1. understand

    Scope: an area of code that is defined at coding time and does not change

    Scope chain: An inside-out structure of nested scopes used to find variables

  2. classification

    Global, function (JS has no block scope (prior to ES6))

  3. role

    Scope: Isolate variables. Variables with the same name can be defined in different scopes without conflict

    Scope chain: Find variables

  4. The difference between scope and execution context

    Scope: static, determined at code time (not at run time), once determined it does not change

    Execution context: dynamic, created dynamically when code is executed and disappears when execution ends

    Connection: The execution context is in the corresponding scope

  5. The interview questions

    1. When I =4, the function body exits, representing the end of the stack, and the following code statement needs to be continued, that is, the stack is removed.

      Log ('global begin:'+ I)//undefined var I =1 foo(1) function foo(I){// I =1 // I =2 // I =3 // I =4 If (I ==4){return} console.log('foo() begin'+ I); if(I ==4){return} console.log('foo() begin'+ I); / / into the stack output 1 2 3 foo (I + 1) / / recursive console log (' foo () end '+ I); 3 2 1} console.log('global end'+ I); // Final output: 1Copy the code
    2. First: note that JS had no block-level scope prior to ES6, so var b=1 causes a variable boost

      C =1 (constant) c=1 (constant) c=1 (constant

      if(! (b in window)){ var b = 1 } console.log(b)//undefined //c = function(){} var c = 1//c = 1 function c(c){ console.log(c) Var c = 3} c(2Copy the code

15. Closure

  1. understand

    Definition: A closure occurs when a nested inner function references a variable of an outer function

    Using chrome tools, closures are essentially an object in an internal function that contains referenced variable properties (key-value pairs)

    Closures are formed under the following conditions :(1) function nesting, (2) local variables of internal functions referencing external functions, and (3) external function calls

  2. role

    Extend the life cycle of local variables so that external functions can manipulate internal local variables

  3. Application of closures

    1. Loop over listening: Add click listening to multiple DOM to read the current subscript

    2. Modularity: Encapsulate some data and the functions that manipulate it, exposing some behavior (modularity is all about passing closures as return values)

    3. The JS framework (jQuery) makes extensive use of closures

    4. Design private variables

    5. Realize the anti – shake function

  4. Closure problems and solutions

    Problems with closures: Because closures cause variables in a function to be stored in memory, memory consumption is high and memory leaks can occur. Therefore, you should not abuse closures, which can cause performance problems for web pages

    Solution: Use the JS garbage collection mechanism to assign the name of the function that is not needed to null

  5. The interview questions

    1. The scope of function execution is determined at coding time and does not change

      Function print(fn) {const a = 200 fn()} const a = 100 function fn() {console.log(a) } print(fn) // 100Copy the code
    2. Each loop starts a timer, but the timer is executed asynchronously. The timer is executed only when the for loop is complete, that is, when I =4

      let i for( i = 1 ; i<=3 ; I ++){setTimeout(function() {console.log(I)}, 0)Copy the code
    3. Js code is executed line by line, paying attention to scope

        let a = 100
      
              function test () {
                  alert(a)
                  a = 10
                  alert(a)
              }
      
              test()
              alert(a)// 100 10 10
      Copy the code
    4. Object.getnamefunc ()() is equivalent to a self-call to the function, with this pointing to the window

      var name='the window'; var object={ name:'my object', getNameFunc:function(){ return function(){ return this.name } } } console.log(object.getNameFunc()()); // the windowCopy the code
    5. Object caches this internally

      Var name = 'the window' var object = {name1:'my object' getNameFunc:function(){var that = this function(){ return that.name1 } } } console.log(object.getNameFunc()())//my objectCopy the code
    6. Hardest interview questions

      function fun(n,o){ console.log(o); return { fun: Function (m){return fun(m,n)}}} var a=fun(0) {// //a=fun(0)===a=fun: Function (m){// return fun(m,n) // return fun(m,n) // return fun(m,n) // / no new closure is generated var b=fun(0).fun(1).fun(2).fun(3).fun(50).fun(2)//undefined 0 1 2 3 50 var c=fun(0).fun(1)//underfined 0 c.fun(2) //1 c.fun(3) //1Copy the code

16. Memory overflow and leak

  1. Out of memory

    A program error that throws an out-of-memory error when the program runs on more memory than is available

  2. Memory leaks

    If the occupied memory is not released in a timely manner, memory leaks accumulate and easily cause memory overflow

  3. Common memory leaks

    1. Unexpected global variables

    2. No timer or callback function to clean up in time

    3. closure

17. Object creation and inheritance modes

  1. Object creation mode

    1. Object constructor created

      var obj = {}
      obj.name = 'Tom'
      obj.setName = function(name){this.name=name}
      Copy the code
    2. Object literal creation

      var obj = {
      	name : 'Tom',
      	setName : function(name){this.name = name}
      }
      Copy the code
    3. Constructor pattern created

      function Person(name, age) {
      	this.name = name
      	this.age = age
      	this.setName = function(name){this.name=name}
      }
      new Person('tom', 12)
      Copy the code
    4. Constructor + stereotype composite pattern created

      function Person(name, age) {
      	this.name = name
      	this.age = age
      }
      Person.prototype.setName = function(name){this.name=name}
      new Person('tom', 12)
      Copy the code
  2. Inheritance mode

    1. Prototype chain inheritance: Inheritance method

      Function Parent(){} parent.prototype. test = function(){} function Child(){} Child. Prototype = new Parent( Child. The prototype. The constructor of the constructor = Child / / prototype to the constructor var Child Child. The Child () = new test () / / call the parent type methodCopy the code
    2. Constructor inheritance: Inherits attributes

      function Parent(xxx){this.xxx = xxx} Parent.prototype.test = function(){} function Child(xxx,yyy){ Parent.call(this, Parent(XXX)} var child = new child ('a', 'b') //child = new child ('a', 'b')Copy the code
    3. Combination of inheritance

      function Parent(xxx){this.xxx = xxx} Parent.prototype.test = function(){} function Child(xxx,yyy){ Parent.call(this, XXX) / / use this constructor. The Parent (XXX)} Child. Prototype = new Parent () / / get the test () the Child. Proptotype. Constructor = Child var Child = new child () //child.Copy the code

Threads and processes

  1. process

    A program execution, he occupies a unique memory space, can be viewed through the Windows task manager

  2. thread

    It is an independent unit of the process, a complete process of the program execution, and the smallest scheduling unit of the CPU

  3. Relationship between

    A process has at least one thread (main) in which the program is executed

19. Browser kernel module composition

  1. The main thread

    Js engine module: responsible for the compilation and running of JS programs

    HTML, CSS document parsing module: responsible for page text parsing

    DOM/CSS module: responsible for DOM/CSS related processing in memory

    Layout and rendering module: responsible for the layout and rendering of pages (objects in memory)

  2. Points thread

    Timer module: Manages timers

    Event response module: responsible for event management

    Web request module: Complex Ajax requests

  3. Js thread

    Js is executed single-threaded (the callback function is also on the main thread)

    H5 puts forward a scheme to realize multithreading: Web Workers –>Worker

    Only main thread update interface

20. Event loop mechanism

  1. 1 JS is single threaded

    All JS code is executed in the main thread

    3 Perform synchronization tasks as soon as they are loaded

    4 Asynchronous tasks will not be executed immediately, but will be handed to the corresponding management module (DOM event management module, Ajax request management module, timer module)

    5 The management module has been monitoring whether the asynchronous task meets the conditions. If the conditions are met, the corresponding callback will be put into callback Quene (callback queue).

    6 After the synchronization task on the main thread is completed, the event Loop(event polling mechanism) queries the callback queue

    Check to see if the event has an executable callback function, and if so hook the callback to the main thread, if not ask later

  2. Asynchronous tasks are divided into micro tasks and macro tasks, which belong to the same queue. The main difference lies in their execution order (after the execution of the macro task, if there are executable micro tasks, the execution of the micro task will proceed to the next macro task).

    Image understanding: like those who go to the bank to queue for business, the clerk in the teller is JS single thread, to queue each person is a macro task, each person will deal with several business, each business is micro task, that is, each macro task with several micro tasks to execute one by one. That is, you can only start the next macro task after all the current microtasks have been processed

    Macro tasks: including overall code script, setTimeout, setInterval, and setImmediate.

    Microtasks: Native Promises (some implemented promises put then methods in macro tasks), process.nextTick, MutationObserver

21. Understanding of phase object and class

  1. class

    1. A class is essentially a function
    2. The methods used by class are defined in class prototype
    3. Class, which also has –proto– pointing to the class’s prototype object
    4. Class is the syntactic sugar of object-oriented programming
  2. object-oriented

    Package a set of properties and methods for instance reuse. It has encapsulation, inheritance and polymorphism

22. A json object

  1. Definition: data transmitted as a string
  2. Type: JSON object, JSON array (key-value pair, key must also be quoted)
  3. Parse ()==> Convert JSON objects (arrays) to JS objects (arrays) using: json.stringify ()==> Convert JS objects (arrays) to JSON objects (arrays), json.parse ()==> Convert JSON objects (arrays) to JS objects (arrays)

23. Object expansion method

Object.defineProperties(object,descrition)

Function: Extends multiple attributes for the specified object definition

–get: Callback function used to get the value of the current attribute

–set: The callback function triggered by modifying the current attribute value and taking the modified value as an argument

Accessor properties: setter,getter one for holding values, one for valuing values

Var obj={} var sex=' male 'object.defineproperties (obj,{sex:{) Get :function(){console.log('get called ',this); return sex; }, // Set :function(value){console.log("set was called ",value,this); sex=value; } } }) console.log(obj.sex); Obj. Sex = 'female' console. The log (obj. Sex);Copy the code

24. Array extension method

// Filter map reduce // Need to filter out the integers less than 100 in the following array, multiply the value of the filtered elements by 2, Let arr1 = arr.filter(item=>item<100) //map: Map (item=>item*2) //reduce: sum up the elements of the specified array. // Two parameters are passed in. Pre: the value returned by the previous traversal defaults to 0 for the first traversal Total = arr2.reduce((pre,n)=>pre+n) // Let result = arr.filter(item=>item<100).map(item=>item*2).reduce((pre,n)=>pre+n)Copy the code

25. Call, apply and bind

Similarity: Both can change the this pointer inside a function

Difference:

  1. Call and Apply call functions directly; Bind does not
  2. Call passes arguments directly separated by commas, and apply passes arguments in arrays

Application scenarios

  1. Call is often used for inheritance
  2. Apply is often associated with arrays, such as maxing and minimising arrays with a Math object implementation
  3. Bind is used when you want to change the this pointer without calling a function immediately, for example by changing the this pointer inside a timer

26. Coriolization of functions

  1. concept

    Change a function that takes multiple arguments to a new function that takes a single argument and returns the remaining arguments.

  2. Function:

    Avoid passing in the same arguments over and over again

  3. The implementation code

    In the curry function, we return a function called currify. We can’t use anonymous functions directly because we need to recursively call currify internally. The parameters are then captured and stored in ARGS. Here’s the key step: If the length of args is greater than fn.length (the length of the function is the length of the parameters the function expects to pass in), this means that enough parameters have been passed in, and fn can be executed using fn.apply. However, if not enough arguments are passed in, currify.bind(null,… args); Pass the current argument list to the function Currify.

    function sum(a, b, c) { return a + b + c; } function curry(fn) { return function currify() { const args = Array.prototype.slice.call(arguments); return args.length >= fn.length ? fn.apply(null, args) : currify.bind(null, ... args); } } var currySum = curry(sum);Copy the code

— — — — — — ES6 part

1. Common new features of ES6

  1. Class class

  2. Iterate over the object method for in/for of

  3. Object and array deconstruction

  4. The REST operator (three-point operator) // replaces arguments

  5. The template string // parses the object destruct, assigning the data in the object to the specified variable

  6. Const, let

  7. Parameter default value

  8. Arrow function

  9. Property of the same name, a simplified version of function

  10. Promise, await&async

  11. module

2. The var, let, const distinction

  1. var:

    Var declares variables that do not have block scope

    Global variables declared by var automatically become properties of the Window object

    [Bug Mc-103866] – Var declaration variables will be raised (declaration will be advanced, but assignment will not, undefined will still be reported)

    Var can be declared repeatedly in the same scope. Let and const are not allowed. Otherwise, an error occurs

  2. let.const

    Let. Const has block-level scope, where let defines variables and const defines constants

3.promise

  1. Definition: A promise is a built-in data structure for JS that represents something that will happen at some point in the future (usually an asynchronous operation)

  2. Function: Solve asynchronous callback, express asynchronous operation in synchronous flow, avoid layer upon layer nested callback function

  3. Status: Initialized successfully (Fullfilled) Failed (Rejected)

  4. Grammar:

    1. Create a Promise instance object (initialize the state of the Promise object to Pending)
    2. Perform asynchronous tasks, such as starting timers and sending Ajax requests
    3. Modify the state of the promise based on the result of asynchronous task execution: successful resolve (), failed Reject ()
    4. The Promise instance object has the then method, which takes two parameters, a callback function for the success and failure states
  5. Applications :(1) implementing timeout handling and (2) encapsulating ajax requests

  6. The implementation loads an image with a promise

    function loadImg(src){ return new Promise((resolve,reject)=>{ const img = document.createElement('img') img.onload = () Resolve (img)}else{reject(new Error(' Error '${img}'))} img.src = SRC})} loadImg(url). Then (img => {img => { console.log(img.width) return img } ).then( img => { console.log(img.height) } ).catch( ex => console.error(ex) )Copy the code

4.symbol data type

Object attribute names in ES5 are all strings, which may cause the same names and pollute the environment

Symbol concept: a primitive data type has been added to ES6 (existing data types: String, number, Boolean, function, object)

Features:

The value of the 1 symbol attribute is unique, resolving naming conflicts

The 2 symbol value cannot be computed with other data, including child string concatenation

3. The symbol attribute is not traversed for in,for of

Built-in Symbol values: In addition to defining the symbol values you use, ES6 provides 11 built-in symbol values that point to ways of using the language.

5. The Iterator iterators

  1. Concept: Iterator is an interface mechanism that provides unified access to different data structures

  2. role

    1. Provide a unified and convenient access interface for various data structures
    2. Allows the members of a data structure to be arranged in some order
    3. ES6 created a new for of command, an iterator interface for consumption
  3. The working principle of

    1. Create a pointer object (traverser object) that points to the starting position of the data structure

    2. The first time the next method is called, the pointer automatically points to the first member of the data structure

    3. The next method is called, and the pointer moves back until it points to the last member

    4. Each call to the next method returns an object containing value and done, {value: the value of the current member, done: Boolean (indicates whether the traversal is complete)}

      {value: undefined, done: true}

  4. Data with native Interator interface (available for traversal)

    (1)Array (2)Arguments (3)set容器(4)map容器 (5)string

  5. Implement an iterator function

    Function iteratorUtil(target){let index = 0 return {// next(){// Next method return index < target.length ? {value:target[index++],done:false} : {value:target[index++],done:true} } } }Copy the code
  6. Arrays and objects implement iteration

    Function iteratorUtil(target){let index = 0 let that = this if(that instanceof) Array){ return { next(){ return index< that.length ? {value:that[index++],done:false} : {value:that[inedx++],done:true}}}}else{let keys = object.keys (that)// return all attributes of the Object as an array let length = keys.length Return {next(){//let key = keys[index++] return index < length? {value:that[keys[index++],done:false} : {value:that[keys[index++],done:true}}}}} // array. prototype[Symbol. Iteratior] = iteratorUtil let arr = [1, 2, 3, 4, Iterator console.log(I);} let person={name:'zty', age:22 } Object.prototype[Symbol.iterator]=iteratorUtil for (let i of person){ console.log(i); }Copy the code

6. Async function

  1. Concept: Solves the asynchronous back problem in the real sense, synchronous streams express asynchronous operations (essentially syntactic sugar for generators)

  2. Grammar:

    1. Definition: async function(){}

    2. Function with await asynchronous operation

    3. Await is followed by an asynchronous task. Await blocks when an asynchronous task is executed and continues to execute the code when the asynchronous task succeeds

      ** defaults to return a Promise object, await followed by a callback equivalent to an asynchronous task

    4. Async + Promise implementation example

      Function promiseUtil(){return new Promise((resolve,reject)=>{setTimeout(()=>{ Resolve (data)},2000)}) // Define async function asyncUtil(){let value1=await promiseUtil() Console. log(' I was the first time ${value1} '); Let value2=await promiseUtil() console.log(' I am the second ${value2} '); } asyncUtil()Copy the code

7. Expand your approach

  1. String method

    (1) Includes(STR): checks whether the specified string is included

    (2) StartsWith(STR) : checks whether the string StartsWith the specified string

    (3) endsWith(STR) : checks whether the string endsWith the specified string

    (4) Repeat(count)

  2. The numerical method

    (1) Binary and octal notation: binary 0b octal: 0o

    (2) number. isFinite(I): check whether the Number isFinite

    (3) Number. IsaNaN (I): check whether it isaNaN

    (4) number. isInteger(I): checks whether it is an integer

    (5) number.parseint (I): Converts the string to the corresponding value

    (6) Math.trunc(I): Remove the decimal part directly

  3. Array methods

    (1) array. from(v): converts a pseudo-array object or traversable object to a true Array

    (2) array. of(vv1,v2,v3): convert a series of values to an Array

    Find (function (value,index,arr) {return true}

    Findindex (function (value, index, arr) {return true}) Findindex (function (value, index, arr) {return true}

  4. Object methods

    (1) object. is(v1,v2): determine whether the two data are completely equal

    (2) Object.assign(target,source1,source2): Copies the attributes of the original Object to the target Object

    (3) Directly manipulate the __proto__ attribute

8. Assignment, shallow copy and deep copy

  1. Assignment: When we assign an object to a new variable, we assign the object’s address on the stack, not the data in the heap. That is, two objects point to the same storage space. If any object is changed, it is the content of the changed storage space. Therefore, the two objects are linked.
  2. Shallow copy: The basic data types of objects before and after the copy do not affect each other. However, the reference types of objects before and after the copy do affect each other because they share the same memory block.
  3. Deep copy: creates a new area of heap memory to store the new object, and makes a recursive copy of the child objects in the object. The two objects before and after the copy do not affect each other

Cloning of 9.

  1. The data type

    1. Basic data type features: Stores the actual data of the object on the stack
    2. Reference data type features: Stores the reference address of the object in the stack, which refers to the instance data in the heap
  2. Distinguish between shallow and deep copies

    Determination: Copy creates new data or copies references to data

    ** Object data stores a reference to an object in stack memory. Direct assignment is a reference to an object

  3. Common copying techniques

    1. Arr.concat () : shallow copy of the array
    2. Arr.slice () : shallow copy of an array
    3. Parse (json.stringify (obj/arr)) : A deep copy of an array or object, but cannot process function data
  4. Wrap a deep copy yourself

    Core idea: clone data cannot have reference data type, if there is, continue to traverse mining until each copy of the object is the basic data type

    / / get data types (form) of the data type string function getType (target) {return Object. The prototype. ToString. Call (target). Slice (8, 1)} function CloneUtil (target){let result // Determine whether clone target is Object or array if(getType(target) === 'Object'){result = {}}else if(getType(target) === 'Array'){result = []}else{return target} for(let I in target){let item = target[I] if(getType(item) === 'Object'||'Array'){ result[i] = cloneUtil(item) }else{ result[i] = item } } return result }Copy the code

10. Set, map

  1. Set

    Definition: unordered non-repeatable collection of multiple values (not arrays but traversable)

    Methods:

    (1) the Set ()

    (2) the Set (array)

    (3) the Add (value)

    (4) the Delete (value)

    (5) from the (value)

    (6) the Clear ()

    (7) Size (equivalent to array length)

  2. Map container (Mapping)

    Definition: A data structure used to access key-value pairs. A key can correspond to only one value and cannot be repeated

11. A written promise

const PENDING = "pending"; // This is a big pity, which is not fulfilled, also not rejected const fulfilled = "filfilled"; // const REJECTED = "REJECTED "; Function myPromise(fn) {console.log(1); function myPromise(fn) {console.log(1); let that = this; that.state = PENDING; that.value = null; that.resolvedCallBacks = []; that.rejectedCallBacks = []; // Both functions have to determine whether the current state is waiting or not, since the specification states that only wait states can change the current state to the corresponding state. And assign the value passed to value // iterate through the callback array and execute function resolve(value) {console.log(2); if (that.state == PENDING) { that.value = value; that.resolvedCallBacks.map(cb => that.value); }}; function reject(value) { console.log(3); if (that.state == PENDING) { that.value = value; that.rejectedCallBacks.map(cb => that.value); }}; Reject () {console. Log (4); // Reject (reject) {console. fn(resolve, reject) } catch (e) { console.log(5); reject(e) } } myPromise.prototype.then = function (onFulfilled, onRejected) { const that = this; console.log(6); // If the parameter is not a function type, you need to create a function to assign to the corresponding parameter. Ondepressing === "function"? onFulfilled : v => v; onRejected = typeof onRejected === "function" ? onRejected : r => { throw r }; // Then there is a set of logic to determine the state, when the state is not wait state, to execute the corresponding function. / / if the state is waiting for the state, then push back the function function if (that) state = = = PENDING) {that. ResolvedCallBacks. Push (onFulfilled); that.rejectedCallBacks.push(onRejected); } if (that.state === FULFILLED) { onFulfilled(that.value) } if (that.state === REJECTED) { onRejected(that.value) } }Copy the code