This article has been submitted from a little sister in the front – Xu Bleaching, this article is a ton of dry goods, the whole high-energy. Hope everyone more likes, comments, attention, to the little sister to continue to write the motivation!

Front end little sister on GitHub

In addition, my little sister has been looking at opportunity Base Beijing recently, and her email address has been attached to GitHub. Welcome to have a pit of students to recommend.

The algorithm,

1. The whole arrangement

Wechat official account: Interesting things in the worldfunction permutate(str) {
    var array = str.split(' ');
    function loop(array, pre = []) {
        if (array.length == 1) {
            return [pre.concat(array).join(' ')];
        }
        let res = [];
        for (let index = 0; index < array.length; index++) {
            var first = array.pop();
            res = res.concat(loop(array, [...pre, first]));
            array.unshift(first);
        }
        return res;
    }
    return Array.from(new Set(loop(array)))
}

Copy the code

2. Binary search

Wechat official account: Interesting things in the worldfunction BinarySearch1 (arr, target) {
    return search(arr, target, 0, arr.length - 1)
    function search (arr, target, from, to) {
        if (from > to) {
            return - 1
        }
        const mid = Math.floor((from + to)/2)
        if (arr[mid] > target) {
            return search(arr, target, from, mid - 1)}else if (arr[mid] < target) {
            return search(arr, target, mid + 1, to)
        } else {
            return mid
        }
    }
}

function BinarySearch2 (arr, target) {
    let from = 0
    let to = arr.length - 1
    let mid = Math.floor((from + to)/2)
    while (from <= to) {
        mid = Math.floor((from + to)/2)
        if (arr[mid] > target) {
            to = mid - 1
        } else if (arr[mid] < target) {
            from = mid + 1
        } else {
            return mid
        }
    }

    return - 1
}
Copy the code

3. Sorting

(1). Bubble sort

Wechat official account: Interesting things in the world/* The NTH cycle determines the NTH */
function BubbleSort (arr) {
    const length = arr.length

    for (let i = 0; i < length; i++) {
        for (let j = 1; j < length-i; j++) {
            if (arr[j] < arr[j - 1]) {
                const temp = arr[j]
                arr[j] = arr[j - 1]
                arr[j - 1] = temp
            }
        }
    }

    return arr
}
Copy the code

(2) quicksort

Wechat official account: Interesting things in the world/* Find a large number on the left and a decimal exchange */ on the right
function QuickSort(arr, low, high) {
    let left = low
    let right = high
    let basic = arr[low]
    while (left < right) {
        while (left < right && arr[right] > basic) {
            right--
        }
        while (left < right && arr[left] <= basic) {
            left++
        }

        if (left < right) {
            const temp = arr[left]
            arr[left] = arr[right]
            arr[right] = temp
        } else {
            const temp = arr[low]
            arr[low] = arr[left]
            arr[left] = temp

            QuickSort(arr, low, left - 1)
            QuickSort(arr, right + 1, high)
        }
    }

    return arr
}
Copy the code

(3). Select sort

Wechat official account: Interesting things in the world/* Find the position of the ith smallest number, put it in position I */
function SelectionSort (arr) {
    const length = arr.length
    for (let i = 0; i < length; i++ ) {
        let minIndex= i
        for (let j = i + 1; j < length; j++) {
            minIndex = arr[minIndex] <= arr[j] ? minIndex : j
        }
        if(minIndex ! == i) {const temp = arr[i]
            arr[i] = arr[minIndex]
            arr[minIndex] = temp

        }
    }
    return arr
}
Copy the code

(4). Insertion sort

Wechat official account: Interesting things in the worldfunction InsertionSort (arr) {
    const length = arr.length
    for (let i = 1; i < length; i++) {
        const temp = arr[i]
        let j
        for (j = i - 1; j >= 0 && temp < arr[j]; j--) {
            arr[j+1] = arr[j]
        }
        arr[j+1] = temp
    }
    return arr
}
Copy the code

(5). Hill sort

An improved version of insertion sort. Insertion sort for numbers in a group of gaps

Wechat official account: Interesting things in the worldfunction ShellSort (arr) {
    const length = arr.length
    let gap = Math.floor(length)
    while (gap) {
        for (let i = gap; i < length; i++) {
            const temp = arr[i]
            let j
            for (j = i - gap; j >= 0 && temp < arr[j]; j = j - gap) {
                arr[j + gap] = arr[j]
            }
            arr[j + gap] = temp
        }
        gap = Math.floor(gap / 2)}return arr
}
Copy the code

(6) merge sort

Wechat official account: Interesting things in the worldfunction MergeSort (arr, low, high) {
    const length = arr.length
    if (low === high) {
        return arr[low]
    }
    const mid = Math.floor((low + high)/2)
    MergeSort(arr, low, mid)
    MergeSort(arr, mid + 1, high)
    merge(arr, low, high)
    return arr

}

function merge (arr, low, high) {
    const mid = Math.floor((low + high)/2)
    let left = low
    let right = mid + 1
    const result = []
    while (left <= mid && right <= high) {
        if (arr[left] <= arr[right]) {
            result.push(arr[left++])
        } else {
            result.push(arr[right++])
        }
    }
    while (left <= mid) {
        result.push(arr[left++])
    }
    while (right <= high) {
        result.push(arr[right++])
    }

    arr.splice(low, high-low+1. result) }const test = [2.34.452.3.5.785.32.345.567.322.5]

console.log(MergeSort(test, 0, test.length - 1))
Copy the code

(7). Heap sort

Wechat official account: Interesting things in the worldfunction HeapSort (arr) {
    const length = arr.length

    // Adjust the initial heap, which actually determines the maximum value
    // But the maximum value is in arr[0]
    for (let i = Math.floor(length/2) - 1; i >= 0; i--) {
        adjustHeap(arr, i, length)
    }

    // Change arr[0](maximum) to next
    for (let i = length - 1; i >=0; i--) {
        const temp = arr[0]
        arr[0] = arr[i]
        arr[i] = temp
        adjustHeap(arr, 0, i)
    }

    return arr
}

// Size is the size of the heap that still needs to be resized
// As each maximum value is determined, the size will get smaller and smaller
function adjustHeap (arr, position, size) {
    const left = position * 2 + 1
    const right = left + 1
    let maxIndex = position
    if (left < size && arr[left] > arr[maxIndex]) {
        maxIndex = left
    }
    if (right < size && arr[right] > arr[maxIndex]) {
        maxIndex = right
    }
    if(maxIndex ! == position) {const temp = arr[position]
        arr[position] = arr[maxIndex]
        arr[maxIndex] = temp
        adjustHeap(arr, maxIndex, size)
    }
    return arr
}
Copy the code

Second, JS foundation

1. The inheritance

  • 1, the prototype chain inheritance, the instance of the parent class as a subclass of prototype, his characteristic is the instance is a subclass instance is also the parent class instance, parent of new prototype methods/properties, subclasses can access, and prototype chain inheritance simple and easy to implement, the disadvantage is that all attributes from the prototype object instance Shared by all, unable to realize multiple inheritance, to the parent class constructor arguments.

  • 2. Construct inheritance, use the constructor of the parent class to enhance the instance of the subclass, that is, copy the instance attributes of the parent class to the subclass, construct inheritance can pass parameters to the parent class, can achieve multiple inheritance, by calling multiple parent objects. However, constructor inheritance can only inherit the instance properties and methods of the parent class, but not the prototype properties and methods. Function consumption cannot be implemented. Each subclass has a copy of the instance function of the parent class, which affects performance

  • 3, instance inheritance, add new features for the parent class instance, return as a subclass instance, the feature of instance inheritance is not limited to call methods, whether new subclass () or subclass () returned objects have the same effect, the disadvantage is that the instance is an instance of the parent class, not an instance of the subclass, does not support multiple inheritance

  • 4, copy inheritance: features: support multiple inheritance, disadvantages: low efficiency, high memory usage (because to copy the properties of the parent class) can not obtain the parent class can not enumerate methods (can not use for in access to)

  • 5, combination inheritance: by calling the parent class construction, inherit the properties of the parent class and retain the advantages of passing parameters, and then through the parent class instance as the prototype of the child class, function reuse

  • 6. Parasitic combination inheritance: Cut off the instance properties of the parent class in a parasitic way, so that when the parent class construction is called twice, the instance methods/properties are not initialized twice, avoiding the disadvantages of combination inheritance

2. This point

(1)

  • 1. Default binding: Globally, this is bound to window by default.

  • 2. Implicit binding: In general, when a function call is contained by a direct object, also called a method call, this is implicitly bound to the direct object.

  • 3. Implicit loss: Implicit loss means that the implicitly bound function loses its binding object and is bound to window by default. Explicit binding: Using the call(), apply(), and bind() methods to bind objects to this is called explicit binding.

  • 4. New binding: If a function or method call is preceded by the keyword new, it constitutes a constructor call. In the case of this binding, it is called a new binding.

    • Constructors usually do not use the return keyword. They usually initialize the new object, and when the body of the constructor completes, it returns explicitly. In this case, the constructor call expression evaluates to the value of the new object.
    • If the constructor uses a return statement but does not specify a return value, or returns a primitive value, then the return value is ignored and the new object is used as the result of the call.
    • If the constructor explicitly returns an object using the return statement, then the value of the calling expression is that object.

(2). Alter this pointer to bind (bind, apply, call);

  • 1. Apply: Calls a method on an object, replacing the current object with another object. For example, B. ply(A, arguments); The way object A applies object B.

  • 2. Call: Calls a method on an object, replacing the current object with another object. For example, b.call (A, args1,args2); Object A calls A method on object B.

  • 3. Bind takes the same arguments as call, except that it returns a function.

(3). Arrow function

  • 1. The arrow function does not have this, so we need to find the value of this by looking at the scope chain. This means that if the arrow function is contained by a non-arrow function, this binds to this of the nearest non-arrow function.
  • 2. The arrow function does not have its own Arguments object, but it has access to the arguments object of the enclosing function
  • 3. It cannot be called with the new keyword, nor does it have a new.target value or stereotype

3. Data type

(1). Basic data types

Undefined, Null, Boolean, Number, String, Symbol

(2).symbol

  • 1. Grammar:

    // Can't use new
    let s = Symbol(a)// We can take a string as an argument that describes the Symbol instance, either for console display or for easy identification when converted to a string.
    let s1 = Symbol('foo');
    let s2 = Symbol('bar');
    
    s1 // Symbol(foo)
    s2 // Symbol(bar)
    
    s1.toString() // "Symbol(foo)"
    s2.toString() // "Symbol(bar)"
    Copy the code
  • 2. Function: Define a unique value

    • 1. Used as the attribute name of the object

      • 1. Not appearing infor... in,for... ofIn the loop, it won’t beObject.keys(),Object.getOwnPropertyNames(),JSON.stringify()To return.
      • 2.Object.getOwnPropertySymbols()Method to get all the Symbol attribute names for a specified object. This method returns an array of all the Symbol values for the current object that are used as attribute names.
      • 3.Reflect.ownKeys()Methods can return all types of key names, including regular and Symbol keys.
    • 2. Used to define a set of constants

      log.levels = {
        DEBUG: Symbol('debug'),
        INFO: Symbol('info'),
        WARN: Symbol('warn')};Copy the code
  • 3. Type conversion:

    • 1. Convert to a string

      String(sym) // 'Symbol(My symbol)'
      sym.toString() // 'Symbol(My symbol)'
      Copy the code
    • 2. Convert to a Boolean value

      Boolean(sym) ! symCopy the code
    • 3. Cannot be converted to numbers

    • 4. Do not operate on other types of values

      let sym = Symbol('My symbol');
      
      "your symbol is " + sym
      // TypeError: can't convert symbol to string
      `your symbol is ${sym}`
      // TypeError: can't convert symbol to string
      Copy the code
  • 4. Properties: Symbol. The prototype. The description

  • 5. Symbol. The for (), Symbol keyFor ()

    • 1. Register the Symbol value in the global environment. It’s not going to be generated again

(3) How to judge the type

Typeof (), instanceof Object. The prototype. ToString. Call ()

  • 1. The typeof operator

    • 1.”undefined” — if this value is undefined;
    • 2.” Boolean “– if the value is a Boolean;
    • 3.”string” — if the value is a string;
    • 4.”number” — if the value is a number;
    • 5.”object” — if the value is an object or null;
    • 6.”function” — if the value is a function.
    • 7.”symbol” — es6’s new symbol type
  • 2. Instanceof: determines whether an object is an instanceof a constructor. We’re going down the prototype chain

  • 3.Object.prototype.toString.call()

    var toString = Object.prototype.toString;
    
    toString.call(new Date); // [object Date]
    toString.call(new String); // [object String]
    toString.call(Math); // [object Math]
    toString.call([]); // [Object Array]
    toString.call(new Number) // [object Number]
    toString.call(true) // [object Boolean]
    toString.call(function(){}) // [object Function]
    toString.call({}) // [object Object]
    toString.call(new Promise((a)= > {})) // [object Promise]
    
    toString.call(new Map) // [object Map]
    toString.call(new RegExp) // [object RegExp]
    toString.call(Symbol()) // [object Symbol]
    toString.call(function *a(){}) // [object GeneratorFunction]
    toString.call(new DOMException()) // [object DOMException]
    toString.call(new Error) // [object Error]
    
    toString.call(undefined); // [object Undefined]
    toString.call(null); // [object Null]
    
    // There are WeakMap, WeakSet, Proxy, etc
    Copy the code

(4). Determine whether it is an array

  • 1.Array.isArray(arr)
  • 2.Object.prototype.toString.call(arr) === '[Object Array]'
  • 3.arr instanceof Array
  • 4.array.constructor === Array

(5). String to number

parseInt(string, radix)

4.CallBack Hell

The way the brain plans things is linear, blocking, single-threaded semantics, but the way callbacks express asynchronous flows is non-linear, non-sequential, which makes it difficult to derive such code correctly. Hard-to-understand code is bad code and leads to bad bugs. We need a more synchronous, more sequential, more blocking way to express asynchrony, just like our brains do.

More importantly, callbacks are subject to inversion of Control because they implicitly give control to a third party (usually a third-party tool that is not under your control!). To call a continuation in your code. Specific logic can be invented to solve these trust problems, but it is more difficult than it should be, can result in heavier, harder to maintain code, and lacks adequate protection, where the damage won’t be discovered until you are affected by bugs.

We need a universal solution to these trust issues. No matter how many callbacks we create, this scenario should be reusable without the overhead of duplicate code.

(1). Why and how Promise is used to solve the INVERSION of Control trust problem

The implementation of Promise can be seen here

The Promise pattern makes this behavior more reliable and reasonable by passing callbacks as parameters with trusted semantics. By reversing the reversal of control for the callback, we put control in a trusted system (Promise) that was designed to make asynchronous coding cleaner. Promise didn’t do away with callbacks, just transferred their arrangement to a trusted intermediary between us and the other tools.

  • Calling callbacks too early;

    • The main concern is whether the code will introduce side effects such as Zalgo (see chapter 2). In this type of problem, a task is sometimes completed synchronously and sometimes asynchronously, which can lead to race conditions.

      By definition, promises don’t have to worry about this, because even if they are completed immediately (similar to new Promise(function(resolve){resolve(42); })) cannot be observed synchronously.

      That is, call THEN (..) on a Promise. Even if the Promise has already been decided, then(..) (See Section 1.5 for more on this).

  • Calling the callback too late (or not being called);

    • Similar to the previous point, the Promise creates an object by calling resolve(..) Or reject (..) The Promise’s then(..) The registered observation callback is automatically scheduled. You can be sure that these scheduled callbacks will be triggered at the next asynchronous event point (see Section 1.5).
  • The callback was not called

    • First, nothing (not even JavaScript errors) prevents a Promise from informing you of its decision (if it does). If you have registered a completion callback and a reject callback for a Promise, the Promise will always call one of them when making a decision.
    • But what if the Promise itself is never decided? Even so, Promise offered a solution that used a high-level abstraction called race:
  • Calling callback too many times;

    • A Promise is defined in such a way that it can only be decided once. If for some reason, the Promise creation code tries to call resolve(..) Or reject (..) Many times, or try to call both, and the Promise will accept only the first resolution and silently ignore any subsequent calls.
    • Since a Promise can only be decided once, anything passed then(..) Registered callbacks are called only once.
  • Failed to pass the required environment and parameters;

    • A Promise can have at most one resolution value (complete or reject).

      If you don’t explicitly decide with any value, then the value is undefined, which is a common JavaScript handler. But whatever this value is, it will be passed to all registered (and appropriate complete or reject) callbacks, whether current or future.

  • Swallow possible errors and exceptions.

    • If a Promise is rejected with a reason (that is, an error message), the value is passed to the rejection callback

(2). Promise, generator, async/await

  • promise

    • Pros: Fixed the callback hell problem
    • Disadvantages: Promises cannot be cancelled, errors need to be caught by callbacks
  • generator

    • The code inside the generator is a series of steps that represent tasks in a natural synchronous/sequential fashion
  • async/await

    • Pros: Clean code, no need to write a lot of then chains like Promise, handles the problem of callback hell

    • Disadvantages: Await transforms asynchronous code into synchronous code. Using await for multiple asynchronous operations without dependencies can result in performance degradation.

5. The load

(1). Method of loading JS asynchronously

  • If your script does not change the contents of the document, add the defer attribute to the

  • Async: HTML5 property, applicable only to external scripts; Also, if there is both Defer and async in IE, defer has a higher priority. The script is executed when the page is complete.

(2) lazy loading and preloading of images

  • Preload: Load images in advance and render them directly from the local cache when the user needs to view them.
  • Lazy loading: The main purpose of lazy loading is to reduce the number of requests or delay requests as a front end optimization of the server.

The nature of the two techniques: the two behave in opposite ways, one loading early, the other loading late or even not loading at all. Lazy loading relieves the pressure on the server front end, while preloading increases the pressure on the server front end.

6. The event

(1). The flow of events

Interactions with javascript in HTML are event-driven, such as the onclick mouse click event, the onScroll page event, and so on. You can add event listeners to the document or elements in the document to order events. To know when these events are invoked, you need to understand the concept of “flow of events.”

What is an event flow: An event flow describes the order in which events are received from the page. The DOM2 level event flow consists of the following stages.

  • Event capture phase
  • In the target stage
  • Event bubble phase

IE only supports event bubbling.

(2). What is event listening

The addEventListener() method, which adds an event handle to the specified element, makes it easier to control events

element.addEventListener(event, function, useCapture);

  • The first argument is the type of the event (such as “click” or “mouseDown “).

  • The second argument is the function that is called after the event is fired.

  • The third parameter is a Boolean that describes whether the event is bubbled or captured. This parameter is optional.

target.addEventListener(type, listener, options: EventListenerOptions);
target.addEventListener(type, listener, useCapture: boolean);
target.addEventListener(type, listener, useCapture: boolean, wantsUntrusted: boolean  );  // Gecko/Mozilla only
Copy the code
interfaceEventListenerOptions { capture? :boolean // indicates that the listener is fired when the type of event capture phase is propagated to the EventTargetonce? :boolean // Indicates that the listener is called at most once after being added. If true, the listener is automatically removed after it is calledpassive? :boolean // If it is set to true, the listener should never call preventDefault(). If the listener still calls the function, the client will ignore it and throw a console warning
}
Copy the code

(3) the difference between mouseover and mouseenter

  • Mouseover: Events are triggered when the mouse moves over an element or its children, so there is a repetitive, bubbling process. The corresponding removal event is mouseout
  • Mouseenter: An event is raised when the mouse removes the element itself (which does not contain its children), so it does not bubble. The corresponding removal event is mouseleave

(4) Event delegation and bubble principle

Brief introduction: Event delegate means that the listener function is not set on the event (direct DOM), but on the parent element, through the event bubble, the parent element can listen to the event triggered on the child element, by judging the event occurrence element DOM type, to make a different response.

Example: the most classic is ul and li tags event listening, for example, we add events, event delegate mechanism, not directly on the li tag, but on the ul parent element added.

Benefits: Suitable for dynamic element binding, new child elements will also have a listener function, and can also have an event trigger mechanism.

(5). The actual application of event agent in the capture phase

You can prevent events from propagating to children at the parent level, or you can perform certain operations on behalf of children.

7. Cross domain

(1).CORS

The basic idea behind CORS(Cross-Origin Resource Sharing) is to use custom HTTP headers to allow the browser to communicate with the server.

For example, a simple request sent using GET or POST has no custom header and a text/plain body. When the request is sent, it needs to be attached with an additional Origin header, which contains the source information (protocol, domain name, and port) of the requested page, so that the server can decide whether to respond based on this header information. Here is an example of the Origin header:

Origin: http://www.nczonline.net If the server finds the request acceptable, it sends back the same source in the access-control-allow-Origin header

Message (you can postback “*” if it is a public resource). Such as:

Access-Control-Allow-Origin: http://www.nczonline.net

If it doesn’t, or if it does but the source information doesn’t match, the browser will reject the request. Normally, the browser handles the request. Note that neither the request nor the response contains cookie information.

(2).IE

Microsoft introduced the XDR(XDomainRequest) type in Internet Explorer 8. Here are some of the differences between XDR and XHR.

  1. Cookies are not sent with the request and are not returned with the response.
  2. Only the Content-type field in the request header can be set.
  3. The response header information cannot be accessed.
  4. Only GET and POST requests are supported.

(3) other browsers

Native support for CORS is implemented through the XMLHttpRequest object

  1. Custom headers cannot be set using setRequestHeader().
  2. Cookies cannot be sent or received.
  3. Calling the getAllResponseHeaders() method always returns an empty string.

(4).JSONP

Wechat official account: Interesting things in the worldfunction handleResponse(response){
alert("You're at IP address" + response.ip + ", which is in " +
response.city + "," + response.region_name);
}
var script = document.createElement("script");
script.src = "http://freegeoip.net/json/?callback=handleResponse"; document.body.insertBefore(script, document.body.firstChild);
Copy the code
  • JSON only supports GET because script tags can only use GET requests;
  • JSONP requires back-end coordination to return data in a specified format.

(5). The agent

Start a proxy server to realize the forwarding of data

(6). Use the iframe

  • window.postMessage
  • Cross Frame(aba)
  • window.name

Lovelock. Coding. Me/javascript /…

(7).window.postMessage

It only supports Internet Explorer 8 and above, other modern browsers are certainly no problem.

(8)

Is not restricted by the same origin policy

  • Add event binding to the receiving party: addEventListener(‘message’, receiveMessage);

  • A party to send data to receive the data side of the window: targetWindow. PostMessage (” Welcome to unixera.com, “” http://iframe1.unixera.com”);

(9). Chilid communicates with Child

There are cross-domain problems, only suitable for communication between different subdomains within the site (set document.domain to the same level of domain)

(10).Cross Frame

This is A general method. In simple terms, A iframe contains B iframe, B iframe calls the relevant interface, and when the call is complete, the location. Href to C iframe that is in the same domain as A iframe. In C iframe, call the method defined in A iframe, pass the result obtained in B iframe as A parameter to the URL to jump to, and obtain the variable through the location.search variable in C iframe.

(11).window.name

The name property of the window object is a special property. After setting window.name, you can run the location.href jump, and the window.name property remains unchanged.

8.Ajax

(1). Implement an Ajax

Wechat official account: Interesting things in the worldvar xhr = new XMLHttpRequest()
// The onReadyStatechange event handler must be specified before calling open() to ensure cross-browser compatibility
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300 || xhr.status ==== 304) {
      console.log(xhr.responseText)
    } else {
      console.log('Error:' + xhr.status)
    }
  }
}
// The third parameter indicates sending the request asynchronously
xhr.open('get'.'/api/getSth'.true)
// The parameter is the data sent as the request body
xhr.send(null)
Copy the code

(2). State of Ajax

  1. Uninitialized. The open() method has not been called.
  2. Start. The open() method has been called, but the send() method has not been called.
  3. To send. The send() method has been called, but no response has been received.
  4. To receive. Partial response data has been received.
  5. To complete. All response data has been received and is ready for use on the client.

(3). Encapsulate native Ajax as a promise

Wechat official account: Interesting things in the worldconst ajax = (url, method, async, data) = > {
  return new Promise((resolve, reject) = > {
    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = (a)= > {
      // All response data has been received and is ready to be used by the client
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText))
        } else if (xhr.status > 400) {
          reject('An error occurred')
        }
      }
    }
    xhr.open(url, method, async)
    xhr.send(data || null)})}Copy the code

9. Garbage collection

Find those variables that are no longer in use and free up the memory they occupy. To do this, the garbage collector does this periodically at fixed intervals (or at predetermined collection times during code execution).

(1). Mark clearance

Tag everything, and then untag the variables referenced in the environment. The rest is useless

(2). Reference counting

Track the number of times each value is referenced. Clearing a variable with zero references ⚠️ causes circular reference problems. Circular references can cause memory leaks if they are present in large numbers.

What is the eval

The eval method acts like a full ECMAScript parser. It takes only one argument, the ECMAScript (or JavaScript) string to execute

  • 1. Poor performance: The engine cannot optimize for scope lookups at compile time
    • 1. The JavaScript engine performs several performance optimizations during compilation. Some of these optimizations rely on being able to do static analysis based on the morphology of the code and determine in advance where all variables and functions are defined so that identifiers can be found quickly during execution.
    • 2. Cannot explicitly know eval(..) at the lexical analysis stage What code is received, how that code changes the scope, and what exactly is the content of the object passed to with to create the new lexical scope. The most pessimistic scenario is that if eval(..) occurs Or with, all optimizations may be meaningless, so the simplest thing is to do no optimizations at all.
  • 2. Spoofing scope: But in strict mode programs, eval(..) It has its own lexical scope at runtime, meaning that declarations in it cannot change the scope in which they reside.

11. Listen for changes in object properties

(a). The ES5

Wechat official account: Interesting things in the worldObject.defineProperty(user,'name', {set:function(key,value){
    // This is how Vue works}})Copy the code

(2). ES6

Wechat official account: Interesting things in the worldvar  user = new Proxy({}, {set:function(target,key,value,receiver){}})Copy the code

You can listen for dynamically added properties. For example, user.id = 1

12. Implement a private variable

  • 1. Configure attributes

    obj={
      name: 'xujiahui'.getName:function(){
        return this.name
      }
    }
    object.defineProperty(obj,"name", {// Cannot enumerate and cannot be configured
    
    });
    Copy the code
  • Code 2.

Wechat official account: Interesting things in the worldfunction product(){
    var name='xujiahui';
    this.getName=function(){
      returnname; }}var obj=new product();
Copy the code

13. Operators

(1).= =and= = =, as well asObject.isThe difference between

  • 1. = =

    • 1. Casts (! =)

    • 2. When converting different data types, the equality and inequality operators follow the following basic rules:

      • 3. If one of the operands is a Boolean, convert it to a numeric value before comparing equality — false converts to 0 and true converts to 1

      • 4. If one of the operands is a string and the other is a number, convert the string to a number before comparing equality;

      • 5. If one of the operands is an object and the other is not, the object’s valueOf() method is called and the resulting values of the basic type are compared according to the preceding rules; These two operators are compared by following the following rules.

      • 6. Null and undefined are equal.

      • 7. Null and undefined cannot be converted to any other value until equality is compared.

      • 8. If one of the operands is NaN, the equality operator returns false and the unequal operator returns true. Important note ⚠️ : the equality operator returns false even if both operands are NaN; Because according to the rule, NaN does not equal NaN.

      • 9. If both operands are objects, compare whether they are the same object. The equality operator returns true if both operands point to the same object; Otherwise, return false.

  • 2.=== : All equals, no conversion

  • 3.Object.is

    • 1. There is no cast.
    • And 2.= = =There are several differences:
      • 1.+ 0 = = = 0.Object.is(+0, -0)To false
      • 2.NaN ! == NaN.Object.is(NaN, NaN)To true

(2) What the.new operator does

Calling the constructor with the new operator actually goes through four steps:

  • Create a new object;
  • 2. Assign the scope of the constructor to the new object (thus this refers to the new object);
  • 3. Execute the code in the constructor (to add properties to the new object);
  • 4. Return the new object.
  • 5. Attach the constructor’s prototype to the instance’s __proto__

An array of 14.

(1). Common methods of array

Push (), pop(), shift(), unshift(), splice(), sort(), reverse(), map(), etc

(2). Deduplicate arrays

Notice how heavy the object is

  • 1. Double loop

    Each time you insert an element, you compare it to the previous element

    var array = [1.1.'1'.'1'];
    
    function unique(array) {
        // res is used to store results
        var res = [];
        for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
            for (var j = 0, resLen = res.length; j < resLen; j++ ) {
                if (array[i] === res[j]) {
                    break; }}// If array[I] is unique, then j equals resLen at the end of the loop
            if (j === resLen) {
                res.push(array[i])
            }
        }
        return res;
    }
    
    console.log(unique(array)); / / / 1, "1"
    Copy the code
  • 2.indexOf

    The principle is the same as the double loop

    var array = [1.1.'1'];
    
    function unique(array) {
        var res = [];
        for (var i = 0, len = array.length; i < len; i++) {
            var current = array[i];
            if (res.indexOf(current) === - 1) {
                res.push(current)
            }
        }
        return res;
    }
    
    console.log(unique(array));
    Copy the code
  • 3. Sort and de-duplicate

    For sorted arrays, you can compare each element to the previous one

    var array = [1.1.'1'];
    
    function unique(array) {
        var res = [];
        var sortedArray = array.concat().sort();
        var seen;
        for (var i = 0, len = sortedArray.length; i < len; i++) {
            // If the first element or adjacent elements are different
            if(! i || seen ! == sortedArray[i]) { res.push(sortedArray[i]) } seen = sortedArray[i]; }return res;
    }
    
    console.log(unique(array));
    Copy the code
  • 4. The Object of key-value pairs

    Store each element as an object key. For example, [‘a’], save as {‘a’: true}

    var array = [1.2.1.1.'1'];
    
    function unique(array) {
        var obj = {};
        return array.filter(function(item, index, array){
            return obj.hasOwnProperty(item) ? false : (obj[item] = true)})}console.log(unique(array)); / / [1, 2]
    Copy the code

    As we can see, there is a problem, because 1 and ‘1’ are different, but this method determines that they are the same value. This is because the key of an object can only be a string, so we can avoid this problem by using Typeof item + item as a string as the key value:

    var array = [1.2.1.1.'1'];
    
    function unique(array) {
        var obj = {};
        return array.filter(function(item, index, array){
            return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})}console.log(unique(array)); / / [1, 2, "1"]
    Copy the code

    However, even so, we cannot correctly distinguish between two objects, such as {value: 1} and {value: 2}, because the result of Typeof item + item is object[Object object], but we can serialize the object using json. stringify:

    var array = [{value: 1}, {value: 1}, {value: 2}];
    
    function unique(array) {
        var obj = {};
        return array.filter(function(item, index, array){
            console.log(typeof item + JSON.stringify(item))
            return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true)})}console.log(unique(array)); // [{value: 1}, {value: 2}]
    Copy the code
  • 5. ES6 Set to heavy

    function unique(array) {
       return Array.from(new Set(array));
    }
    Copy the code
    function unique(array) {
        return [...new Set(array)];
    }
    Copy the code
  • 6.ES6 Map

    function unique (arr) {
        const seen = new Map(a)return arr.filter((a) = >! seen.has(a) && seen.set(a,1))}Copy the code

Three, advanced skills

1. Anti-shake throttling

(1). The throttle

It only executes once in n seconds, so throttling will dilute the frequency of the function

(2). Image stabilization

Last count. For example, “Stop typing for 5s before sending a request.”

3. Array expansion

  • 1. The recursion
Wechat official account: Interesting things in the worldfunction flat1 (arr) {
    let result = []
    arr.forEach(element= > {
        if (Array.isArray(element)) {
            result = result.concat(flat1(element))
        } else {
            result.push(element)
        }
    });
    return result
}
Copy the code
  • 2.toString
function flat2 (arr) {
    // There is a defect that cannot maintain the previous type after toString
    return arr.toString().split(', ')}Copy the code
  • 3.reduce
Wechat official account: Interesting things in the worldfunction flat3 (arr) {
    // Flat1 is the same as flat1
    return arr.reduce((pre, next) = > {
        return pre.concat(Array.isArray(next) ? flat3(next) : next)
    }, [])
}
Copy the code
  • 4. The rest operator
Wechat official account: Interesting things in the worldfunction flat4 (arr) {
    while (arr.some(item= > Array.isArray(item))) {
        [].concat('1', 2, [3, 4])
        // The concat method itself expands the array in the argumentarr = [].concat(... arr); }return arr;
}
Copy the code
  • 5.ES6 flat
Wechat official account: Interesting things in the worldfunction flat5 (arr: any[]) {
    The flat() method removes empty items from the array
    return arr.flat(Infinity)}Copy the code

4. Drag and drop

Wechat official account: Interesting things in the worldvar DragDrop = function(){
  var dragging = null; 
  function handleEvent(event){
    
    // Get the event and target
    event = EventUtil.getEvent(event);
    var target = EventUtil.getTarget(event);
    
    // Determine the event type
    switch(event.type){
      case "mousedown":
        if (target.className.indexOf("draggable") > - 1){
          dragging = target; 
        }
        break;
      case "mousemove":
        if(dragging ! = =null) {// Specify the location
          dragging.style.left = event.clientX + "px";
          dragging.style.top = event.clientY + "px";
        }
        break;
      case "mouseup": 
        dragging = null;
        break; }};// Public interface
  return {
    enable: function(){
      EventUtil.addHandler(document."mousedown", handleEvent);
      EventUtil.addHandler(document."mousemove", handleEvent);
      EventUtil.addHandler(document."mouseup", handleEvent);
    },
    disable: function(){
      EventUtil.removeHandler(document."mousedown", handleEvent);
      EventUtil.removeHandler(document."mousemove", handleEvent);
      EventUtil.removeHandler(document."mouseup", handleEvent); }}} ();Copy the code
  • 1. The DragDrop object encapsulates all the basic features of drag and drop. This is a singleton object and uses the module pattern to hide some of the implementation details. The dragging variable is initially null and will hold the dragging element, so when the variable is not null, you know that something is dragging. The handleEvent() function handles all three mouse events in the drag-and-drop function. It first gets the event reference to the image and the event target. After that, you use a switch statement to determine which event style to fire. When the MouseDown event occurs, the target class is checked to see if it contains the “draggable” class, and if so, the target is stored in dragging. This technique makes it easy to identify draggable elements using markup languages rather than JavaScript scripts.

  • 2. The Mousemove situation of handleEvent() is the same as the previous code, but check whether THE DRAGGING is NULL from DRAGGING to dragging. When it is not NULL, the DRAGGING element is known to be the dragging element, and it is placed in place. The Mouseup case simply reset the DRAGGING to NULL, invalidating the judgment in the Mousemove event.

  • 3.DragDrop also has two public methods :enable() and disable(), which simply add and remove all event handlers accordingly. These two functions provide additional control over drag-and-drop functionality.

  • 4. To use the DragDrop object, simply include the code on the page and call Enable (). Drag and drop is automatically enabled for all elements that contain a “draggable” class, as shown in the following example:

    <div class="draggable" style="position:absolute; background:red"> </div>
    Copy the code

    Note that in order for an element to be dragged and dropped, it must be absolutely positioned.

5.once

Wechat official account: Interesting things in the worldfunction once (func) {
  var done;
  return function () {
    if(! done) { func.apply(null.arguments)
      done = true}}}Copy the code
Wechat official account: Interesting things in the worldfunction onlyDoOne = once(function() {
  console.log('1')})Copy the code

6.promise

A Promise is an object that holds an event that will end in the future. It has two characteristics:

  • A Promise object represents an asynchronous operation. There are three states: pending, fulfilled, and rejected. Only the result of an asynchronous operation can determine the current state. That’s where promise came from

  • Once the state of a Promise object changes, it can only change from “pending” to “fulfilled” or from “pending” to “rejected”. As long as these two conditions occur, the state of a Promise object becomes frozen and will not change again. This is called “fixed resolved”

7.sleep

With the Promise

  1. function sleep (ms) {
      return new Promise((resolve) = > {
        window.setTimeout(resolve, ms)
      })
    }
    
    sleep(1000).then((a)= >{
      console.log('Already sleep 1000ms')})Copy the code
  2. function sleep (ms) {
      return new Promise((resolve) = > {
        window.setTimeout(resolve, ms)
      })
    }
    
    // Call with async/await
    async function test () {
      var example = await sleep(1000)
      console.log('Already sleep 1000ms')}Copy the code
  3. // Use generator to define sleep function
    function *sleep (ms) {
      yield new Promise((resolve) = > {
        window.setTimeout(resolve, ms)
      })
    }
    sleep(1000).next().value.then((a)= >{
      console.log('Already sleep 1000ms')})Copy the code

Iv. Browser

1. The cache

(1) by cache location

  • 1.Service Worker
    • 1. Resources in this cache can be cleared in two ways: manually calling the APIcache.delete(resource)Or the capacity exceeds the limit, and the browser is completely empty.
    • 2. If the Service Worker does not hit the cache, it is usually usedfetch()Method continues to fetch the resource. The browser then goes to the memory cache or disk cache for the next cache search. Note: Passes the Service Workerfetch()Method is marked as, even if it does not hit the Service Worker cache, or even if it actually made a network requestfrom ServiceWorker.
  • 2.Memory Cache: Disabled if TAB is disabled
    • 1. The memory cache mechanism ensures that if there are two identical requests on a page (for example, two)srcThe sameimageAnd the twohrefThe samelink) will actually only be requested at most once to avoid waste.
    • 2. When retrieving cached contents from the memory cache, the browser ignores the examplemax-age=0.no-cacheSuch header configuration. For example, there are several identical pagessrcAre read from the memory cache even though they may be set to uncached. This is because memory cache is only used for a short period of time and in most cases has a lifetime of only one browse. whilemax-age=0It is generally read semantically as “don’t use it next time you browse”, so it does not conflict with memory cache.
    • 3. But if the webmaster really doesn’t want a resource in the cache, even for a short period of time, then it needs to be usedno-store. With this header configuration, even the memory cache will not store it, and therefore will not read from it.
  • 3.Disk Cache: The Disk Cache determines which resources can be cached and which resources cannot be cached strictly based on the various fields in the HTTP header. Which resources are still available and which are obsolete and need to be rerequested. When the cache is hit, the browser reads the resource from the hard disk, which is slower than reading from memory, but much faster than a network request. Most of the cache is from the disk cache.
  • 4. Network request: If a request does not find a cache in any of the above three locations, the browser will officially send a network request to get the content. Then it’s easy to think of adding this resource to the cache in order to increase the cache hit ratio of subsequent requests. To be specific:
    • 1. The handler in the Service Worker determines whether to store the Cache Storage (additional Cache location).
    • 2. According to the HTTP header related fields (Cache-control.PragmaEtc.) determine whether to save to disk cache
    • 3. Memory cache Stores a reference to a resource for future use.

(2) By failure strategy

Memory cache is the browser’s own optimization to speed up cache reading. It is not controlled by the developer, nor is it constrained by HTTP headers. It is a black box. Service workers are additional scripts written by developers, cached in a separate location, appear late, and are not widely used. The most familiar is actually the Disk cache, also known as the HTTP cache (because unlike memory cache, it obeys the HTTP header fields). The common concepts of force caching (strong caching), contrast caching (negotiated caching), and cache-control also fall into this category.

Force caching (also called strong caching)

Forcing caching directly reduces the number of requests and is the cache strategy that improves the most. Its optimization covers the three phases of request, processing and response

Fields that cause mandatory caching are cache-control and Expires.

  • Expires.

    • HTTP1.0
    • Because the time is absolute, the user may change the local time on the client. As a result, the browser determines that the cache is invalid and requests the resource again. In addition, even without taking into account confidence modifications, time differences or errors can cause time inconsistency between the client and server, invalidating the cache.
    • It’s too complicated to write. A time string with more than one space or less than one letter will result in an invalid attribute and invalidate the setting
  • Cache-control

    • HTTP1.1

    • High priority

    • Max-age: indicates the maximum valid time

      Must-revalidate: If the max-age time is exceeded, the browser must send a request to the server to verify that the resource is still valid.

      No-cache: Although the literal meaning is “do not cache”, the client is actually required to cache the content, but whether to use the content is determined by subsequent comparison.

      No-store: Literally “don’t cache.” All content is not cached, including force and comparison.

      Public: All content can be cached (both client and proxy servers, such as CDN)

      Private: All content can be cached only by the client, not by the proxy server. The default value.

Comparison cache (Negotiation cache)

The comparison cache is the same as no cache in terms of the number of requests, but if it is 304, only a status code is returned and there is no actual file content, so the saving in response volume is the optimization point.

  • Last-Modified & If-Modified-Since
    • Server throughLast-ModifiedThe field tells the client when the resource was last modified
    • The browser records this value in the cache database along with the content.
    • The next time the browser requests the same resource, it retrieves its own cache for the “indeterminate” cache. So in the request header will be the lastLast-ModifiedIs written to the request headerIf-Modified-Sincefield
    • The server willIf-Modified-SinceThe value of andLast-ModifiedField for comparison. If yes, it is not modified, and the response is 304; Otherwise, it is modified, and the 200 status code is responded and the data is returned.
    • If the resource is updated at a rate of less than seconds, then the cache is not available because its time unit is at least seconds.
    • If the file is dynamically generated by the server, the update time for this method is always the time it was generated, although the file may not have changed and therefore does not serve as a cache.
  • Etag & If-None-Match
    • Etag has a higher priority than last-Modified
    • EtagStores the special identifier of the file (usually hash generated), and the server stores the fileEtagField.
    • And then the process andLast-ModifiedConsistent, justLast-ModifiedThe field and the update time it represents have changed toEtagField and the file it represents hashIf-Modified-SinceTurned out to beIf-None-Match.
    • The server does the same comparison, returning 304 for a hit and 200 for a miss.

(3).Ajax solves the browser cache problem

  • 1. Before the ajax request plus anyAjaxObj. SetRequestHeader (” the if-modified-since “, “0”).

  • 2. Before the ajax request plus anyAjaxObj. SetRequestHeader (” cache-control “, “no – Cache”).

  • 3. Add a random number after the URL: “fresh=” + math.random ().

  • Add a time rub to the end of the URL: “nowtime=” + new Date().gettime ().

  • $.ajaxSetup({cache:false}) $.ajaxSetup({cache:false}) So all of the Ajax on the page will execute this statement but there’s no need to save the cache record.

2. Principles of browser rendering

(1).Render Tree

  • Don’t show,display: noneElements of) are not generated
  • There are theRenderTree, we know the style of all the nodes, then calculate their size and position on the page (layout), and finally draw the nodes onto the page (draw).
  • Since browsers use streaming layouts, yesRender TreeThe computation of is usually done by traversing only once,buttableWith the exception of its internal elements, they may require multiple calculations, often taking three times as long as the equivalent element, which is why you should avoid usingtableOne reason for the layout.

(2). Redrawn

When the layout is not affected due to changes in geometric attributes of nodes or changes in styles, it is called redrawing, such as Outline, visibility, color, background-color, etc. The cost of redrawing is high, because the browser must verify the visibility of other node elements in the DOM tree.

(3) the backflow

Backflow is a layout or geometric property that needs to be changed and is called backflow. Backflow is a key factor that affects browser performance, because it involves changing the layout of part of the page (or the entire page). The backflow of one element can result in subsequent backflow of all of its child elements, as well as of the following nodes in the DOM, ancestor node elements.

(4). Browser optimization

Most modern browsers are batch update layout through the queue mechanism, the browser will put the modification operations in the queue, at least one browser refresh (16.6 ms) will empty the queue, but when you get the layout information, the queue may affect the properties or methods return value of the operation, if not, the browser will be forced to empty the queue, Trigger backflow and redraw to ensure that the correct value is returned.

Mainly include the following attributes or methods:

  • offsetTop,offsetLeft,offsetWidth,offsetHeight
  • scrollTop,scrollLeft,scrollWidth,scrollHeight
  • clientTop,clientLeft,clientWidth,clientHeight
  • width,height
  • getComputedStyle()
  • getBoundingClientRect()

Therefore, we should avoid frequent use of the above properties, they will force the render refresh queue.

(5). Reduce redrawing and reflux

  • 1.CSS

    • 2. Replace top with transform

    • 3. Use visibility instead of display: None, as the former will only cause a redraw and the latter will cause backflow (layout change)

    • 4. Avoid using the table layout. A small change may cause the whole table to be rearranged.

    • 5. Change classes at the very end of the DOM tree as much as possible. Reflux is inevitable, but it can be reduced. Changing the class as far as possible at the end of the DOM tree limits the scope of backflow and affects as few nodes as possible.

    • 6. Avoid setting multiple layers of inline style. CSS selectors are matched from right to left to avoid too many layers of nodes.

      <div>
        <a> <span></span> </a>
      </div>
      <style>
        span {
          color: red;
        }
        div > a > span {
          color: red;
        }
      </style>
      Copy the code

      For the first style, the browser just needs to find all the spans in the page and set the color, but for the second style, the browser needs to first find all the spans, then the A tag on the span, and then the div tag, The recursion is complicated by setting the color of the span tag that meets this condition. So we should try to avoid writing CSS selectors that are too specific, and then try to keep the HTML hierarchy flat by adding as few meaningless tags as possible.

    • 7. Apply the animation effect to an element whose position is Absolute or fixed to avoid affecting the layout of other elements. This is only a redraw, not a backflow. See the requestAnimationFrame discussion.

    • 8. Avoid using CSS expressions that may cause reflux.

    • 9. Set a node that is frequently redrawn or reflow to a layer. This layer will prevent the rendering behavior of this node from affecting other nodes, such as will-change, video, iframe, etc. The browser will automatically turn this node into a layer.

    • 10.CSS3 hardware acceleration (GPU acceleration), CSS3 hardware acceleration allows transform, opacity, and filter animations not to cause reflux redraw. Other properties of the animation, such as background-color, will still cause backflow redrawing, but it will improve the performance of these animations.

  • 2.JavaScript

    • 1.Avoid frequent manipulation of stylesIt’s better to rewrite it all at oncestyleProperty, or define the style list asclassAnd change it onceclassProperties.
    • 2.Avoid frequent operationsDOM, create adocumentFragment, apply allDOM manipulation, and then add it to the document.
    • 3. Avoid reading properties that cause reflow/redraw too often. If you do need to use them more than once, cache them with a single variable.
    • 4. Use absolute positioning for elements with complex animations to keep them out of the flow of the document, otherwise it will cause frequent backflow of parent and subsequent elements.

(6) when does.js parse?

  1. <script>

    • During rendering, if you encounter JS, stop rendering and execute JS code.

    • If JS needs to operate on CSSOM, it will first let CSSOM build, then execute JS, and finally build the DOM

  2. <script async>

    • Execute the imported JavaScript asynchronously, and execute JS after loading, blocking the DOM
  3. <script defer>

    • Delay execution. HTML parsing is not blocked when the JavaScript file is loaded. The execution phase is delayed until the HTML tag is parsed.

5. Basic computer skills

1. Computer network

(1).TCP three-way handshake

  • First handshake: Both ends are CLOSED at first. The Client sets the FLAG bit SYN to 1, generates a value seq=x randomly, and sends the packet to the Server. The Client enters the SYN-sent state, waiting for the Server to confirm.

  • 2. Second handshake: After receiving the packet, the Server knows that the Client requests to establish a connection by the flag bit SYN=1. The Server sets both the flag bit SYN and ACK to 1, ACK =x+1, randomly generates a value seq=y, and sends the packet to the Client to confirm the connection request. When the Server enters the SYN-RCvd state, the operating system allocates TCP cache and variables for the TCP connection.

  • 3. Third handshake: After receiving the acknowledgement, the Client checks whether the ACK is X +1 and 1. If it is correct, the ack flag bit is set to 1 and ACK =y+1. At this time, the operating system allocates TCP cache and variables for the TCP connection and sends the data packet to the Server, which checks whether the ACK is Y +1. Check whether the ACK value is 1. If yes, the connection is ESTABLISHED and the Client and Server enter the ESTABLISHED state. The three-way handshake is completed.

(2). CDN principle

The full name of the CDN is Content Delivery Network. The basic principle of CDN is to widely use various cache servers and distribute these cache servers to areas or networks where users’ access is relatively centralized. When users visit websites, the global load technology is used to point users’ access to the nearest cache server that works normally, and the cache server directly responds

(4). The DNS

  • Browser cache: The browser caches DNS records at a certain frequency.
  • Operating system cache: If the required DNS record is not found in the browser cache, look for it in the operating system.
  • Route cache: Routers also have DNS caches.
  • DNS server of an ISP: An ISP is short for Internet Service Provider. An ISP has a special DNS server to handle DNS query requests.
  • Root server: If the ISP’s DNS server cannot find it, it will send a request to the root server for recursive query (the DNS server first asks the root DNS server for the IP address of the.com DNS server, then the baidu DNS server, and so on).

(5). Common HTTP request headers

HTTP headers can be divided into generic headers, request headers, response headers, and entity headers

Head agreement instructions
Accept The acceptable response content-types.
Accept-Charset Acceptable character set
Accept-Encoding The encoding of acceptable response content.
Accept-Language List of acceptable response content languages.
Accept-Datetime An acceptable version of the response content in terms of time
Authorization Indicates the authentication information about the HTTP authentication resource
Cache-Control Specifies whether caching is used in the current request/reply.
Connection The type of connection that the client (browser) wants to use preferentially
Cookie An HTTP protocol Cookie Set by the previous server via set-cookie (see below)
Content-Length The length of the request body in base 8
Content-MD5 The binary MD5 hash value (digitally signed) of the contents of the request body, as a Base64 encoded result
Content-Type MIME type of the request body (used in POST and PUT requests)
Date The date and time the message was sent (toRFC 7231″HTTP date “format defined in the
Expect Indicates that the client requires a specific behavior from the server
From The email address of the user who initiated the request
Host Indicates the domain name of the server and the port number that the server listens to. If the requested port is the standard port (80) for the corresponding service, the port number can be omitted.
If-Match The operation is performed only when the entity provided by the client matches the corresponding entity on the server. This is primarily used in methods such as PUT to update a resource only if it has not been modified since the user last updated it.
If-Modified-Since Return 304 unmodified if the corresponding resource has not been modified
If-None-Match Allows 304 Not Modified to be returned if the corresponding content has Not been Modified, referring to the hypertext transfer protocol entity tag
If-Range If the entity has not been modified, return the missing part or parts. Otherwise, the entire new entity is returned
If-Unmodified-Since A response is sent only if the entity has not been modified since a certain time.
Max-Forwards Limits the number of times the message can be forwarded by the proxy and gateway.
Origin Initiate a campaign againstCross-domain resource sharingThis request requires the server to include an access-control-allow-Origin header in the response, indicating the sources allowed by Access Control.
Pragma These fields may arise at any time in the request/response chain, depending on the specific implementation.
Proxy-Authorization Authentication information used to authenticate the agent.
Range Represents a request for part of an entity, with byte offset starting with 0.
Referer Represents the previous page visited by the browser, which can be thought of as a link to the previous page that brought the browser to the current page. The word “Referer” is actually the word “Referrer”, but it was misspelled in the RFC production standard, and has since been used incorrectly.
TE The Encoding the browser expects to receive for the transport: You can use the value in the response protocol header transfer-encoding (and you can also use “trailers” for the chunking of the data) to indicate that the browser wants to receive some additional fields after the last block of size zero.
User-Agent The identity string of the browser
Upgrade Requires the server to upgrade to a higher protocol version.
Via Tell the server which agent made the request.
Warning A general warning that there may be an error in the entity content body.

(5) OSI seven-layer model

Application layer: File transfer, common protocols HTTP, SNMP,FTP,

Presentation layer: data formatting, code conversion, data encryption,

Session layer: Establishes and disconnects a session

Transport layer: provides the end-to-end interface, TCP, UDP

Network layer: Selects routes for packets, IP, ICMP

Data link layer: transmits frames with addresses

Physical layer: Transmission of data in binary data form over physical media

(5). The difference between TCP and UDP

  • 1.UDP
    • 1. No connection
    • 2. For packets, it is a carrier of packets
    • 3. Unreliable, no congestion control
    • 4. Efficient, with header overhead of only 8 bytes
    • 5. Supports one-to-one, one-to-many, many-to-many, and many-to-one
    • 6. Suitable for live broadcast, video, voice, meeting and other real-time requirements
  • 2.TCP
    • 1. Connection-oriented: Connect before transmission
    • 2. Reliable transmission
    • 3. Flow control: The sender does not send too fast to exceed the processing capacity of the receiver
    • 4. Congestion control: When the network load is too much, it can limit the sending rate of the sender
    • 5. No delay guarantee is provided
    • 6. The minimum bandwidth is not guaranteed

(6) Why shake hands three times and wave four times

  • 1. Wave four times
    • 1. Because it is both sides have established A connection, so both of us to release their connection, A to B issued A release connection request, and he is going to release the link showed no longer send data to B, B received at this time after the release of the links of A request, send A confirmation to A, A, can no longer send B data, it is in A state of FIN – WAIT – 2, But at this point, B can also transmit data to A. At this point, B sends A disconnection request to A. UPON receipt, A sends an acknowledgement to B. B closes the connection. A also closes the connection.
    • 2. Why does the state of time-wait exist? It is because the last acknowledgement may be lost.
    • Of course TCP is not 100% reliable.
  • 1. Three-way handshake: To prevent the invalid connection request packet segment from being suddenly transmitted to the server, resulting in an error

(7). What is the difference between WebSocket and Ajax? What are the application scenarios of WebSocket

WebSocket was born to solve the unidirectional problem of THE HTTP protocol itself: requests must be initiated by the client to the server, and then the server responds. This request-response relationship cannot be changed. This is fine for general web browsing and access, but it’s a problem when we need the server to proactively send a message to the client, because the previous TCP connection has been released and the client is nowhere to be found. In order to get data from the server in a timely manner, programmers have pained themselves to come up with all kinds of solutions that compromise on the HTTP framework. No way. So you either poll regularly, or you rely on a long connection — the client makes a request, the server holds the connection in its hand, waits for a message, and if it times out, the client asks again — but you know what I mean, it’s just a poll with fewer requests and better real-time performance.

WebSocket is fundamentally a technical solution to this problem: by name, it borrows ports and headers from the Web to create connections, and the subsequent data transfer is almost exactly the same as tcp-based sockets, but encapsulates many of the functions that we had to do manually when developing sockets. For example, native support for WSS security access (sharing ports and certificates with HTTPS), validation when creating connections, automatic splitting of message packets from data frames, and so on.

In other words, we used to only use HTTP protocol in the browser, but now we have a Socket, which is a much better Socket.

After understanding the background and features of WebSocket, you can answer the question of whether it can replace AJAX:

For two-way communication between server and client, WebSocket is simply the best choice. If it weren’t for the few older browsers still in service, all polling, long connections, etc., would have been obsolete long ago. Libraries (such as http://Socket.IO and SignalR) that integrate multiple two-way push messages have lost their main selling point of being compatible with all browser versions, automatically identifying older browsers and using different connections. All new browsers are Compatible with WebSockets. Just use the original. As an aside, this is much like jQuery, which rose rapidly when native JS was hard to use, and slowly became less important as other libraries and native JS absorbed many of its advantages. However, a large proportion of AJAX usage scenarios are still in the traditional request-response format, such as getting JSON data, Posting forms, and so on. These functions can be implemented with WebSocket, but just as we defined the request-based HTTP protocol on top of TCP for data flow, we need to define a new protocol on top of WebSocket, at least with a request ID to distinguish between requests for each response data.

… But why build a new wheel one layer at a time? Isn’t it simpler and more sophisticated to just use AJAX?

In other cases, when transferring large files, images, or media streams, it’s best to use HTTP instead. If you must use WebSocket, at least create a new channel for this data, rather than the real-time connection used for push messages. Otherwise, the serial WebSocket will be completely blocked.

So websockets can be flexible, simple, and efficient for two-way transmission and push messages, but they are not very useful for ordinary request-response processes, which are much more cumbersome and even less efficient than ordinary HTTP requests.

Each technology has its own advantages and disadvantages, in the place suitable for it can play the greatest strengths, and see its several advantages on the occasion of the full range of promotion, may backfire.

We used WebSocket ourselves to great effect when we developed an Internet robot that could communicate with a mobile phone. Instead of replacing HTTP, it replaces the TCP-based Socket used for communication.

Advantages are:

Previously, there was some complicated authentication after the Socket connection, and control instructions were prevented from being sent for unauthenticated connections. This is no longer necessary. The url where the WebSocket connection is established can carry the authentication parameters. If the authentication fails, it can be rejected directly without setting the status.

The original implementation of a set of similar SSL asymmetric encryption mechanism, now completely unnecessary, directly through WSS encryption, but also to ensure the credibility of the certificate;

In the past, we had to define the format of the Socket data, set the length and flag, and deal with the problems of sticking packets and subcontracting. Now the WebSocket directly receives the complete data packet, and does not have to deal with it by ourselves.

The front-end Nginx allows direct forwarding and load balancing, making deployment much easier

(8).TCP/IP network model

  • 1. The TCP/IP model is a collection of network protocols designed to enable the exchange of information between computers,

  • 2. The four-layer architecture of TCP/IP model is link layer, network layer, transport layer and application layer from bottom to top

  • 3. Link layer is responsible for establishing circuit connections and is the physical basis of the entire network. Typical protocols include Ethernet, ADSL, etc.

  • 4. The network layer is responsible for allocating addresses and transmitting binary data. The main protocol is IP.

  • 5. The transport layer is responsible for transmitting text data. The main protocol is TCP

  • 7. The application layer is responsible for transmitting various final forms of data and is the layer directly dealing with user information. The main protocols are HTTP and FTP

2. The HTTP protocol

(1). Common request methods

The HTTP 1.0

  • 1.GET: Requests data from the specified resource
  • 2.POST: Submit the data to be processed to the specified resource, for example
    • 1. Submit the form
    • 2. Post messages to bulletin boards, newsgroups, mailing lists, blogs, or similar article groups;
  • 3.HEAD
    • 1. It is similar to a GET request, but the response is returned with no specific content, only the header
    • 2. Request only the header of the resource
    • 3. Check the validity of the hyperlink
    • 4. Check whether the web page is modified

HTTP1.1

  • 1.PUT: Replaces or creates a specified resource
  • 2.DELETE: Deletes the specified resource

HTTP2.0

  • 1.OPTIONS: To obtain the communication OPTIONS supported by the destination resource, such as the request mode supported by the server, etc.

  • 2.TRACE: Implements loop-back testing of messages along the path to the target resource, providing a practical debug mechanism.

  • 3.CONNECT

    • 1. For the proxy server

    • 2. In THE HTTP protocol, the CONNECT method opens a two-way communication channel between the client and the requested resource. It can be used to create a tunnel. For example, CONNECT can be used to access sites using the SSL (HTTPS) protocol. The client requires the proxy server to use the TCP connection as a tunnel to the destination host. Then the server establishes a connection with the destination host instead of the client. After the connection is established, the proxy server sends or receives TCP message flows to the client.

All generic servers must support the GET and HEAD methods. All other methods are optional.

  • 1. Security: Among the request methods defined in this specification, the GET, HEAD, OPTIONS, and TRACE methods are defined as safe
  • 2. Idempotent: PUT, DELETE, and safe methods are idempotent.
  • 3. Cacheability: GET, HEAD, and POST. But most implement only GET and HEAD cacheable
    • 1. Indicates that the browser automatically caches the data for subsequent requests. Unless there are relevant policies in response

(2). The difference between GET and POST

  • 1. The GET parameter is passed through the URL, and the POST parameter is put in the request body.

  • 2. Get requests pass parameters in the URL with a length limit, while POST does not.

  • 3. Get is less secure than POST because parameters are directly exposed in the URL and cannot be used to pass sensitive information.

  • 4. The GET request can only be encoded by the URL, while the POST request supports multiple encoding modes

  • 5. Get requests are cached actively by the browser, while POST supports multiple encoding methods.

  • 6. Get request parameters are completely preserved in the browsing history, while POST parameters are not.

  • 7.GET and POST are essentially TCP links. There is no difference. However, due to HTTP regulations and browser/server restrictions, they are different in the application process.

(3). The HTTP status code

  • 1xx (Informational): The request is received and being processed
  • 2XX (Successful): The request has been successfully received, understood, and accepted
  • 3xx (Redirection): indicates Redirection
  • 4XX (Client Error): The request contains incorrect syntax or cannot be completed
  • 5xx (Server Error): Indicates a Server Error

(4) What’s the specific difference between 301 and 302

  • 301: permanently moved, the requested page has been permanently moved to the new location, the server returns this response, will automatically redirect the requestor to the new location

  • 302: Historical movement, where the server is currently responding to requests from a different location, but the requester should continue to use the original location for future requests,

3. Operating system

(1). The difference between process and thread

  • 1. Process is the basic unit that concurrently executes a program to allocate and manage resources during execution. It is a dynamic concept, the basic unit that competes for the resources of a computer system.

  • 2. Threads are part of a process. A process without threads can be considered single-threaded. Threads, sometimes referred to as lightweight processes or lightweight processes, are a basic unit of CPU scheduling.

A program has at least one process, and a process has at least one thread. Resources are allocated to the process, and all threads under the same process share the resources of the process

(2). Which resources are shared and which resources are not shared by the thread

  • 1. Shared resources are as follows

    • 1. Heap: Since the heap is carved out of process space, it is naturally shared; So everything that comes out of new is shared (global heap and local heap on 16-bit platform, local heap is exclusive)
    • 2. Global variables: they are independent of a particular function, and therefore independent of a particular thread; So it’s shared
    • 3. Static variables: Although local variables are “stored” in the code in a function, they are stored in the same place as global variables, in the heap. BSS and.data segments, which are shared
    • 4. Common resources such as files: This is shared and threads using these common resources must be synchronized. Win32 provides several ways to synchronize resources, including signals, critical sections, events, and mutexes.
  • 2. Exclusive resources

    • 1. Stack: The stack is exclusive
    • Registers: this may be misunderstood, because the registers of the computer are physical, isn’t the value different for each thread? In fact, the thread is stored in the copy, including the program counter PC

(3) What are the communication modes between processes

  • 1. Anonymous pipe: A half-duplex communication mode in which data flows only in one direction and can only be used between related processes
  • 2. Advanced pipeline: another program is started as a new process in the current program process, then this process is a child process of the current program,
  • 3. Named pipe: is also a half-duplex communication mode, but allows communication between unrelated processes
  • 4. Message queue: Message queue is a linked list of messages, stored in the kernel and identified by the message queue identifier. Message queue overcomes the disadvantages of little signal transmission information, the channel can only carry the plain byte stream and the buffer size is limited
  • 5. Semaphore: A semaphore is a counter that can be used to control the access of multiple processes to a shared resource. It is often used as a locking mechanism to prevent other processes from accessing a shared resource while a process is accessing it.
  • 6. Signal: Used to notify the receiving process that an event has occurred
  • 7. Shared memory: Shared memory is the mapping of memory that can be accessed by other processes. This shared memory is created by a single process, but can be accessed by multiple processes. Shared memory is the fastest IPC method and is often used in conjunction with other communication mechanisms
  • 8. Sockets: Can be used for process communication between different machines

Sixth, front advance

1.VUE

(1). Life cycle of VUE

A Vue instance has a full life cycle, that is, from start to create, initialize the data, compile the template, mount the Dom, render → update → render, destroy, etc., we call this the life cycle of Vue. Colloquially, the process from creation to destruction of a Vue instance is the life cycle.

Each component or instance goes through a complete lifecycle, which is divided into three phases: initialization, running, and destruction.

  • 1. The instance and component are created by new Vue(), which will initialize the event and lifecycle, and then execute the beforeCreate hook function. At this time, the data has not been mount, it is just a shell, which cannot access the data and the real DOM, and usually does not do operations

  • 2. Mount data, bind an event and so on, and then execute created function, already can use this time to the data, also can change the data, change the data here will not trigger the updated function, can in here before rendering a second chance to change the data from bottom, not trigger other hook function, can generally make initial data access here

  • 3. Next, start to find the template corresponding to the instance or component, compile the template for the virtual DOM and put it into the render function to prepare rendering, and then execute beforeMount hook function. In this function, the virtual DOM has been created and is about to render. This is the last opportunity to change the data before rendering, without triggering any other hook functions. This is usually the place to do the initial data fetch

  • > < p style = “word-break: inherit; word-break: inherit;”

  • 5. When the data of a component or instance changes, it immediately executes beforeUpdate. Then vue’s virtual DOM mechanism reconstructs the virtual DOM and compares it with the last virtual DOM tree using diff algorithm and then renders it again

  • 6. When the update is completed, execute updated, the data has been changed, dom has been rerendered, and the updated virtual DOM can be operated

  • 7. Execute beforeDestroy immediately after calling the $destroy method in some way, usually doing some cleaning up here, such as clearing timers, clearing non-instruction binding events, etc

  • 8. Data binding, listening… Only the DOM shell is left. Run the Destroyed command to check the destruction

(2).Vue bidirectional binding principle

Vue data bidirectional binding is achieved by data hijacking combined with the publisher – subscriber pattern. The object.defineProperty () method is used to redefine the Object’s get and set property values.

2.Webpack

Webpack is a static Module Bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a dependency graph that contains every module the application needs, and then packages all of those modules into one or more bundles.

(1). Differences between Webpack and gulp

Gulp emphasizes the front-end development workflow. You can build the entire front-end development process of a project by configuring a series of tasks, defining the transactions that the tasks handle (such as file compression and merging, Sprite diagrams, starting server, versioning, etc.), and then defining the execution order for gulp to execute those tasks.

Webpack is a front-end modular solution with more emphasis on module packaging. We can treat all resources (images, JS files, CSS files, etc.) in the development as modules, process the resources through loader and plugins, and package them into front-end resources suitable for production environment deployment.

3. The modular

(1). How to understand front-end modularity

Front-end modularity is complex file programming a separate module, such as JS files, etc., divided into separate modules to facilitate reuse (reuse) and maintenance (version iteration), this will lead to the problem of module interdependence, so there are commonJS specification, AMD, CMD specification, etc., And WebPack, a tool for js packaging (compiling, etc.)

(2). Talk about Commonjs, AMD and CMD

A module is a file that implements a specific function. With a module, you can easily use other people’s code, and you can load any module with any function you want.

  • 1.Commonjs: Modularity starts on the server side, modularity is defined synchronously, each module is a separate scope, module output, modules.exports, module load require() imports the module.

  • 2.AMD: Chinese name asynchronous module definition meaning.

    • 1. Require JS implements the AMD specification

      • 1. It mainly solves the following two problems.

        • 1. Multiple files have dependencies. The dependent file must be loaded to the browser before the dependent file
        • 2. The browser will stop rendering the page when loading. The more files loaded, the longer the page will be unresponsive.
      • 2. Syntax: requireJS defines a function define, which is a global variable used to define modules.

      // Define the module
      define(['dependency'].function(){
        var name = 'Byron';
        function printName(){
          console.log(name);
        }
        return {
          printName: printName
        };
      });
      
      Copy the code
      // Load the module
      require(['myModule'].function (my){
        my.printName();
      }
      Copy the code
    • 2. Summary of AMD specification: the require() function loads dependencies asynchronously, so the browser does not become unresponsive, and the callback function it specifies will only be executed if the previous module loads successfully. Since the page will stop rendering when loading js, we can load JS asynchronously, and if we need to rely on some of them, we can also asynchronously rely on them, and then execute some methods.

4. Simple implementation of Node Events module

Introduction: The observer mode, or subscription mode, defines a one-to-many relationship between objects. Multiple observer objects listen to a topic object at the same time. When an object changes, all objects that depend on it are notified.

The Events module in Node is implemented using the observer mode:

Wechat official account: Interesting things in the worldvar events=require('events');
var eventEmitter=new events.EventEmitter();
eventEmitter.on('say'.function(name){
  console.log('Hello',name);
})
eventEmitter.emit('say'.'Jony yu');
Copy the code

In this case, eventEmitter emits the Say event, receives it through On, and outputs the result. This is the implementation of a subscription mode.

  • 1. Implement simple Event module emit and on methods

    function Events(){
        this.on=function(eventName,callBack){
            if(!this.handles){
                this.handles={};
            }
            if(!this.handles[eventName]){
                this.handles[eventName]=[];
            }
            this.handles[eventName].push(callBack);
        }
        this.emit=function(eventName,obj){
            if(this.handles[eventName]){
                for(var i=0; o<this.handles[eventName].length; i++){this.handles[eventName][i](obj); }}}return this;
    }
    Copy the code
  • 2. With Events defined, we can now start calling them:

    var events=new Events();
    events.on('say'.function(name){
        console.log('Hello',nama)
    });
    
    // The result is Jony Yu output after calling through emit
    events.emit('say'.'Jony yu');
    Copy the code
  • 3. Each object is independent

    Because of the new method, the generated object is different each time, so:

    var event1=new Events();
    var event2=new Events();
    event1.on('say'.function(){
        console.log('Jony event1');
    });
    event2.on('say'.function(){
        console.log('Jony event2');
    })
    
    Event1 and Event2 have no influence on each other
    'Jony event1' 'Jony event2'
    event1.emit('say');
    event2.emit('say');
    Copy the code

5. Optimize performance

  • 1. Reduce requests: Merge resources, reduce HTTP requests, Minify/gzip compression, webP, image lazyLoad.

  • 2. Speed up requests: Pre-resolve DNS, reduce the number of domain names, parallel loading, and CDN distribution.

  • 3. Cache: HTTP cache requests, offline cache manifest, offline data cache localStorage.

  • 4. Rendering: JS/CSS optimization (avoid using CSS expressions), load order (put CSS stylesheet at the top and javascript at the bottom), server rendering, Pipeline.

Seven, tail

See here, is not amazed at the little sister’s strength? Like, comment, follow and share!!