A HTML&CSS.

1- What is SEO optimization?

Seo is search engine optimization: using search engine rules to improve your site’s natural ranking within the relevant search engines.

  • Page Theme optimization

    Be realistic and write down the name of your website. The name of your website should be reasonable and preferably include the main content of your website.

  • Page header optimization

    <meta name="keywords"   content="" />Explain your web page keywords to search engines;<meta name="description"    content=""/>Tell search engines the main content of your site;Copy the code
  • Hyperlink optimization

    Do not have empty links in the page

    Write the hyperlink, the title property, as a standard, either to alert visitors or to let search engines know where it is going.

  • Image optimization

    Each tag has Alt and title attributes. The Alt attribute is used to show text instead of images when they can’t be displayed, and for SEO, it gives search engines the opportunity to index images on your site

  • Set h1-H6 tags on the page

  • Optimize site performance and improve site loading speed

2- Page adaptation

Adaptive is when the page content automatically ADAPTS to the screen size.

There are several ways to achieve adaptation:

  • 1. Simple scenarios to achieve adaptive: floating, page center, element width is not written fixed and set percentage automatic matching size. In this way, when the page width changes, the above features can be used to achieve a simple adaptive effect.
  • 2. If the actual development of complex scene requirements, generally by writing multiple sets of CSS code, and then use media query technology, let the page according to different screen sizes to load different code modules to achieve the purpose of adapting to different screens. This approach requires multiple sets of code, which is a lot of work, but has a separate set of CSS code for devices with different screen sizes, making it easier to maintain.
  • 3. Responsive layout, which automatically adjusts the page display effect according to different screen sizes to achieve adaptive (also using media query technology). Responsive layouts generally include raster system layouts, Flex layouts. At the heart of the Bootstrap framework is the grid system.

The core of adaptive Web design is the Media Query module introduced by CSS3. Automatically detects the screen width and loads the corresponding CSS file

Related layout:

1- Media query + REM

  • Media means devices (mobile devices, PC devices)
  • Query refers to detecting which device belongs to
  • Media query: Enables web pages to preview normally on different devices by querying which device they belong to

2-REM + VW (Layout)

3-REM layout (isometric scaling layout)

4- Flexible layout (100% layout, flow layout)

5- Holy Grail layout

  • The Grail layout is a three – column adaptive layout with fixed width on both sides. The middle bar is placed in front of the document flow and rendered first. The goal is to solve the three-column layout.

6- Twin wing layout

The Holy Grail layout adds relative positioning to the middle bar, along with the left and right attributes. The effect is that the three columns are separate (if gaps are visible), while the twin wing layout has a nested div inside the middle bar, and the content is written inside the nested div. Then set margin-left and margin-right to the nested div, so that the left and right columns are above the middle column, and the middle column remains the same100% width, except that the content of the middle column is displayed in the middle by the value of margin.Copy the code

7 – the grid layout

3 – HTML 5 new features

(1) HTML5 provides new elements to create better page structure:

<article>Represents a piece of content that is independent of context<aside>Define the sidebar content of the page.<header>Represents a content block in a page or the header of the entire page.<footer>A footnote that represents a block of content in a page or the entire page<mark>Define highlighted text (SPAN)<nav>The section that defines the navigation link.<section>Define sections (sections, sections) in a document.<main>Represents the main content of the page (IE incompatible)<hgroup>A grouping of headings<time>Define a date or time.<figure>Represents an independent paragraph of content,<figcaption>Add a title to it (the position of the first or last child element)<dialog>The tag defines a dialog box (dialog box) similar to wechat<canvas>The canvasCopy the code

(2) THE HTML5

element is used for drawing graphics, which is completed by script (usually JavaScript).

(3) HTML5 Audio, Video multimedia tags

<video src=""></video>
<audio src=""></audio>
Copy the code

(4) HTML5 has several new form input types. These new features provide better input control and validation.

Color, date, datetime, datetime-local, email, month, number, range, search, tel, time, URL, weekCopy the code

(5) HTML5 has the following new form elements:

<datalist>		<input>The tag defines a list of options. Use this element in conjunction with the input element to define the possible values for the input.<output>		<output>Tags define different types of output, such as the output of a script.Copy the code

(6) HTML5

4 – range of new features

(1) CSS3 selector

  • With CSS3, you can create rounded borders, add shadow boxes,

(2) CSS3 border (Borders)

  • CSS3 includes several new background attributes that provide greater control over background elements.

(3) CSS3 gradient

  • Linear Gradients – Down/up/left/right/diagonal
  • Radial Gradients – defined by their centers

(4) CSS3 conversion and deformation

(5) CSS3 transition and animation

(6) CSS3 multiple columns

(7) CSS3 box model

  • In CSS3, a number of new UI features have been added to adjust element size, box size, and border, including the following UI attributes

(8) CSS3 telescopic layout box model (elastic box)

  • CSS3 Flexible Box (or Flexbox) is a layout that ensures that elements behave appropriately when a page needs to adapt to different screen sizes and device types.

(9) CSS3 media query

Media refers to various devices (mobile devices, PC devices) and queries refer to which devices to detect// Media query: enables web pages to preview normally on different devices by querying which device they currently belong to
Copy the code

5- Positioning Methods in the CSS (Common)

1.Absolute location refers to the nearest parent element that has the location attribute.2.(relantive) Relative positioning, referring to their own position for positioning.3.(Fixed) Fixed location based on the browser window.4.(staticDefault positioning, left to right, top to bottom streaming layout.Copy the code

6- How to center a box horizontally and vertically? (Elements are centered horizontally and vertically)

        body{
            /* First type: elastic box */
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .box{
            width: 200px;
            height: 100px;
            background: paleturquoise;
            /* * * * * * * * * * * * * * * * * * * * * * *
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto; 
            /* * * */
            position: absolute;top: 50%;left: 50%;
            margin-top: -50px;/* Half the height of the element itself */
            margin-left: -100px; /* Half the width of the element itself */
            /* * * * * * * * * * * * * * * * * * * * * *
            position: absolute;
            top: 50%;left: 50%;
            transform: translate(-50%, -50%);
        }
Copy the code

7- Image centered horizontally and vertically (image sizes inconsistent)

  • 1, horizontal center: add text-align:center to the img parent element
  • (1) add the same tag as span before and after img, change span to inline-block, and add width:0; Vertical-align :middle (3) IMG Vertical-align :middle

8 – box model

// Standard box model: standard mode total width =width+ margin-right + margin-right border
// Weird box model: weird mode total width =width+margin
Copy the code

The difference between 9-PX, REM, EM and VW

-px is a fixed unit relative to the screen resolution of a display. -em is relative to the font size of the parent element. For example, if the font size of the parent element is 16px, then 1em=16px and 2em=32px. - REM is relative to the font size of the root element (HTML), the default browser font size is 16px, so 1REM =16px, 2rem=32px, according to the width of the device, combined with the media query (@media) for adaptive layout. Minus vw is the actual width of the window, 1vw=1% The actual width of the window.Copy the code

10- Draw a 0.5px line

1.Draw a 1px line;2.Using the zoom property, you canCopy the code
transform: scale(0.5);
Copy the code

11- Elastic box properties

-Flex is a CSS box layout method that controls the arrangement of child elements by changing the attributes of the parent element. - flex-direction Specifies the direction of the main axis. - flex-wrap Specifies whether to justify a child element when space is insufficient. - justify- Content Specifies the alignment of the main axis Alignment of multiple axes. This property has no effect if the project has only one axisCopy the code

Flex: What does 1 stand for

- flex:1Flex is a contraction of flex-grow, flex-shrink, and flex-basis. The default value is flex:1 1Auto (there is residual space to enlarge, space is insufficient to reduce); - flex-grow: specifies the size of an element. Default1Even if there is spare space, it will not enlarge; - flex-shrink: indicates the shrink ratio of elements. The default value is shrink1, that is, if there is not enough space, the element will shrink; - flex-basis: indicates the main axis space occupied by the project. The default value is auto, which is the original size of the project.Copy the code

2. JavaScript

What are the 1-JS data types?

  • Basic data types

      // string: string,
      // Number: Number,
      // Boolean: Boolean,
      // undefined: undefined,
      // null: null type,
      // symbol(ES6 added) :
    Copy the code
  
  // Complex data types (reference data types)
  // object: indicates an object. Including the function/array/object
Copy the code

2- Find the most common element in the array, and the number of occurrences

let arr=[1.3.2.4.5.66.1.3.4.5.6.1.1.2.3.1.55.6.7.8.90.0];
Copy the code

Method 1: Use objects

  • 1. Create an empty object, traverse the target array, add object attributes and increase the number of times according to whether the array element exists in the object.

  • 2. Iterate through the array to obtain the result object, and then iterate through the object to find the most elements and the number.

  let arr = [
    1.3.2.4.5.66.1.3.4.5.6.1.1.2.3.1.55.6.7.8.90.0,];function findMost(arr) {
    if(! arr.length)return;
    if (arr.length === 1) return 1;
    let res = {};
    let maxName,
      maxNum = 0;
    // go through the number group
    arr.forEach((item) = > {
      res[item] ? (res[item] += 1) : (res[item] = 1);
    });
    / / traverse res
    for (let r in res) {
      if(res[r] > maxNum) { maxNum = res[r]; maxName = r; }}return "The element that occurs most frequently is :" + maxName + ", the frequency of occurrence is :" + maxNum;
  }
  console.log(findMost(arr));// The element with the most occurrence is :1, and the occurrence is :5
Copy the code

Method 2.? modified

  • Get rid of object traversal and put the comparison into array traversal
  let arr = [
    1.3.2.4.5.66.1.3.4.5.6.1.1.2.3.1.55.6.7.8.90.0,];function findMost(arr) {
    if(! arr.length)return;
    if (arr.length === 1) return 1;
    let res = {};
    let maxName,
      maxNum = 0;
    // go through the number group
    arr.forEach((item) = > {
      res[item] ? (res[item] += 1) : (res[item] = 1);
      if(res[r] > maxNum) { maxNum = res[r]; maxName = r; }});return "The element that occurs most frequently is :" + maxName + ", the frequency of occurrence is :" + maxNum;
  }
  console.log(findMost(arr));// The element with the most occurrence is :1, and the occurrence is :5
Copy the code

Method 3. Use the reduce method of array

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code
  • The Reduce method takes two arguments, the first a function and the second an initial value

  • The function takes four arguments: the computed result or initial value, the current value, the current index, and the array itself

function findMost (arr) {
  if(! arr.length)return;
  if (arr.length === 1) return 1;
  let maxName, maxNum = 0
  let res = arr.reduce((res, currentNum) = > {
    res[currentNum] ? res[currentNum] += 1 : res[currentNum] = 1
    if (res[currentNum] > maxNum) {
      maxNum = res[currentNum]
      maxName = currentNum
    }
    return res
  }, {})
  return 'The element that occurs most often is :' + maxName + ', the occurrence times are :' + maxNum;
}
Copy the code

3 – in jsStack memoryandHeap memory

The js engine stores variables in two main locations, heap memory and stack memory.

  • Stack memory is mainly used to store variables of various basic types, including Boolean, Number, String, Undefined, Null, ** and Pointers to object variables. At this time, the stack memory feels like a linear arrangement of space, with each small unit roughly equal in size.

  • Heap memory is mainly responsible for storing variable types such as Object

  • Variables in stack memory are usually of known size or have an upper bound, and are considered simple storage. The object type data stored in heap memory is generally unknown in terms of size.

4- THE Url address is divided into several parts

Protocol, domain name, port number, and path

For a URL like thishttp:/ / www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhereWe can use javascript to get each part of it1.window.location.href The entire URl string (in the browser, the entire address bar)./ / www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

2.window.location.protocol The protocol part of the URL. The returned value in this example is HTTP:3.window.location.host Host part of the URL In this example, the returned value is www.x2y2.com4.window.location.port Specifies the port portion of the URL if the default is used80Port (update: Even if:80), then the return value is not the default80This example returns a value:""

5.window.location. pathName Specifies the path part of the URL (that is, the file address)./fisker/post/0703/window.location.html

6.windowIn addition to assigning values to dynamic languages, we can also assign values to static pages and use javascript to obtain the values we believe should be the parameters of the.location.search query. ver=1.0&id=6

7.window.location.hash anchor point This example returns the value #imhereCopy the code

5- Interview question: Implement the function of obtaining URL search field parameters

1-js provides methods

URL = `? username=zhangsan&password=123456&type=get&type=post`;
function search(url) {
  console.log(url);
  let params = new URLSearchParams(url);
  let username = params.get("username");
  let password = params.get("password");
  let type = params.getAll("type");
  console.log(username, password);
  console.log(type); // ["get", "post"]
  let obj = {};
  obj.username = username;
  obj.password = password;
  obj.type = type;
  console.log(obj);
}
search(URL);
/* {username: "zhangsan", password: "123456", type: Array(2)} password: "123456" type: (2) ["get", "post"] username: "zhangsan" */
Copy the code

2- Array, string methods

var search =
      "? uname=dingdin&upwd=12345&favs=swimming&favs=running&favs=music";
    function searchObj(str) {
      / / remove?
      var str = str.slice(1);
      // Split string according to ampersand
      var arr = str.split("&");
      // define an empty obj to hold the object
      var obj = {};
      // Loop over the split array
      for (var p of arr) {
        // Split according to "="
        var arr2 = p.split("=");
        / / deconstruction
        var [name, value] = arr2;
        // if name in obj is undefined, fill in the value, otherwise connect
        if (obj[name] == undefined) {
          obj[name] = value;
        } else{ obj[name] = [].concat(value, obj[name]); }}return obj;
    }
    var a = searchObj(search);
    console.log(a);
    /* {uname: "dingdin", upwd: "12345", favs: Array(3)} favs: (3) ["music", "running", "swimming"] uname: "dingdin" upwd: "12345" __proto__: Object */
Copy the code

6- Nine cross-domain methods and solutions

First, what is cross-domain?

  1. What is the same origin policy?
    • Browsers don’t allow us to send requests to other people, only to our own servers
    • When we try to send a request to someone else’s server, the browser blocks it
    • What is “someone else’s server”?
      • When the request protocol/domain name/port number is either different, then it is someone else’s server
      • The same-origin policy is triggered at this point
      • A request that triggers the same origin policy is called a cross-domain request
    • The same protocol, the same domain name, the same port,
  2. When does cross-domain occur
    • If a protocol, subdomain name, main domain name, or port number is different, the domain name is counted as different. Requests for resources between different domains are “cross-domain.”

Second, cross-domain solutions

Hash + iframe 4. Window. name + iframe 5. PostMessage 6. Cross-domain resource sharing (CORS) 7, Cross-domain nginx proxy 8, cross-domain Node.js middleware proxy 9, cross-domain WebSocket protocol

Third, summary

  • CORS supports all types of HTTP requests and is the fundamental solution for cross-domain HTTP requests
  • JSONP supports only GET requests. The advantage of JSONP is that it supports older browsers and can request data from sites that do not support CORS.
  • Both the Node middleware proxy and the Nginx reverse proxy have no restrictions on the server through the same origin policy.
  • In daily work, the cross-domain solutions used more are CORS and NGINX reverse proxies

What did 7-New do?

Implementation process

  • A new empty object is created;
  • Set the prototype of the object to the function’s prototype object;
  • Make the function’s this point to the object and execute the constructor code (adding attributes to the new object);
  • Determine the return value type of the function and, if it is a value type, return the created object. If it is a reference type, an object of that reference type is returned.

Concrete implementation:

function objectFactory() {
  let newObject = null;
  let constructor = Array.prototype.shift.call(arguments);
  let result = null;
  // Check whether the argument is a function
  if (typeof constructor! = ="function") {
    console.error("type error");
    return;
  }
  // Create an empty object whose prototype is the constructor's Prototype object
  newObject = Object.create(constructor.prototype);
  // Point this to the new object and execute the function
  result = constructor.apply(newObject, arguments);
  // Determine the returned object
  let flag = result && (typeof result === "object" || typeof result === "function");
  // Determine the return result
  return flag ? result : newObject;
}
// How to use itObjectFactory (constructor, initialization parameter);Copy the code

8 – what isbackflowandredraw?

  • Backflow occurs when a part of the DOM node tree needs to be rebuilt due to changes in the element’s size, layout, hiding, etc.
  • When some elements in the node tree need to update their attributes, and these attributes only affect the appearance and style of the elements, but do not affect the layout, it is called redraw
  • ** Note: ** Backflow always causes redraw, but redraw does not necessarily cause backflow, and backflow is more costly

9-js execution context

JS code before execution, JS engine always need to do some preparatory work, this work is actually to create the corresponding execution context;

There are only three types of execution contexts: global execution context, function context, and eval context; Because eval is not normally used

1. Global execution context

There is only one global execution context, known as the Window object, which we can access directly in the global scope through this
Copy the code

2. Function execution context

  • There can be an infinite number of function execution contexts, one being created each time a function is called; Note that multiple calls to the same function create a new context.

The execution context stack (hereinafter referred to as the execution stack) is also called the call stack. The execution stack is used to store all the contexts created during the execution of the code and has the feature OF LIFO (Last In First Out).

10 – Es6New features

  1. Const and let

    • Different from the var

      • Let and const ‘do not allow variables to be declared repeatedly

      • Variables declared by lets and const ‘are not parsed at pre-parsed time (i.e., no variable promotion)

      • Variables declared by let and const are scoped by all code blocks

    • Let and const

      • The value of a variable declared by let can be changed. The value of a variable declared by const ‘cannot be changed

      • Let can be declared without an assignment, const must be declared with an assignment

  2. Template string

    • ‘(back quotes) : indicates a string;

    • And the difference between single quotes and double quotes

      • Backquotes can be written on a new line
      • Backquotes concatenate variables directly inside a string
  3. Deconstruction assignment

    • Deconstruction extracts values from arrays and objects and assigns them to unique variables

    • Deconstruction object

      const obj = {
        name: 'Jack'.age: 18.gender: 'male'
      }
      let { name, age, gender } = obj
      Copy the code

      The preceding {} indicates that I’m going to get a member from the object obj

      Name, age, gender all have to be members of OBJ

    • Deconstruction array

      const arr = ['Jack'.'Rose'.'Tom']
      let [a, b, c] = arr
      Copy the code

      The preceding [] indicates that the arR array is ready to fetch members

      A, B, and c correspond to indexes 0, 1, 2 in this array

  4. Object shorthand

    • When a variable name is used as the attribute value of an object attribute, only the variable name is written if the variable name is the same as the attribute name. In this case, the variable name is used as the attribute name and the variable value as the attribute value.

    • Method shorthand: The name of the method is the property name of the object, and the value of the method is the property value of the object

    • Merge object:

      			var zhangsan = {name:'zhangsan'};
      			var lisi = {age:18};
      			let res = Object.assign(zhangsan,lisi)
      			console.log(zhangsan)//{name: "zhangsan", age: 18}
      			console.log(res)//{name: "zhangsan", age: 18}
      			console.log(lisi)//{age: 18}
      Copy the code
  5. Expansion operator

    • . , called the expansion operator

    • It expands an array

      let arr = [1, 2, 3, 4, 5]//-> 1, 2, 3, 4, 5 console.log(... Arr) // 1 2 3 4 5 console.log(1,2,3,4,5)Copy the code
    • This can be used when merging arrays

      let arr = [1.2.3.4]
      let arr2 = [...arr, 5]
      console.log(arr2)
      Copy the code
    • It can also be used by merging objects

      let obj = {
        name: 'Jack'.age: 18
      }
      letobj2 = { ... obj,gender: 'male'
      }
      console.log(obj2)
      Copy the code
    • It can also be used when a function is passing arguments

      let arr = [1.2.3]
      function fn(a, b, c) {
        console.log(a)
        console.log(b)
        console.log(c) } fn(... arr)// equivalent to fn(1, 2, 3)
      function box(. arr){
        console.log(arr) [1.2.3.4.5.6]
      }
      box(1.2.3.4.5.6)
      Copy the code
  6. Residual parameter (variable parameter)

    Use the expansion operator to expand an array into multiple elements, and bind multiple elements into an array with the remaining arguments. The remaining parameters also use three consecutive points (…). Representation, which allows you to represent an indefinite number of elements as arrays.

    • Use 1: When assigning a variable to an array value:

      const order = [20.17.18.67.1.50."cheese"."eggs"."milk"."bread"];
      const [total, subtotal, tax, ...items] = order;
      console.log(total, subtotal, tax, items);
      Copy the code
    • ES6 uses ** argument objects ** for functions with variable arguments

      function sum() {
        let total = 0;  
        for(const argument of arguments) {
          total += argument;
        }
        return total;
      }
      // In ES6, the residual argument operator is more concise and readable:
      function sum(. nums) {
        let total = 0;  
        for(const num of nums) {
          total += num;
        }
        return total;
      }
      Copy the code
  7. ES6 arrow function

    • Important: ** arrow functions can only be abbreviated function expressions, not declarative functions
    • Characteristics of the arrow function
      1. There is no this inside the arrow function; the arrow function’s this is the context’s this
      2. There’s nothing inside the arrow functionargumentsThe set of parameters
      3. If the function has only one line parameter, it can be omitted(a)The rest of the case must be written
      4. If there is only one line of code in the function body, do not write it{}And automatically return
  8. Parameter Default Value

  • That is, when I don’t pass an argument, I use the default value, and when I pass an argument, I use the argument that I pass
  • In ES6 we can write default values directly in the line arguments of functions
  • This default value of the way arrow function can also be used
  • Note: the ** arrow function also needs to write () to a parameter if you want to use the default value.

11-Es5 and Es6 inheritance differences

  • Es5 Inheritance: The basic idea is to use prototype chains to make one reference type inherit the properties and methods of another reference type (implemented by Prototype and constructor) : add the parent class to the prototype chain (or this) of a subclass

  • Inheritance in ES5 is implemented through the stereotype or constructor mechanismCopy the code
  • Es6 Inheritance: Basic idea: Implementing inheritance through the extend keyword, a subclass can inherit all the methods and attributes of its parent class. A subclass must call a super() method in a Construc () method, because a new subclass does not have its own This object, but inherits the this object of its parent class;

  • ES6 throughclassThe keyword defines the class, which has constructors that pass between classesextendsClose key implementation inheritance. 5. Subclasses must be inconstructorMethod callsuperMethod, or an error is reported when creating a new instance. Because subclasses don't have their ownthisObject that inherits from its parent classthisObject, and then process it. If you don't callsuperMethod, subclasses don't getthisObject. 6. Pay attention tosuperThe keyword refers to an instance of the parent class, that is, of the parent classthisObject. Note: In the subclass constructor, callsuperBefore usethisKeyword, otherwise an error is reportedCopy the code

    Essence: Inherits the parent class using the extend keyword, and then inherits its properties and methods

12- Macro and micro Tasks JS execution mechanism (event loop)

(1) JS execution mechanism (event loop)

  • Js is single-threaded and the code is executed sentence by sentence

    A single thread can execute only one piece of code at a time. If a time-consuming operation is encountered during the execution, it will stop by default and wait for the operation to complete. In this case, the page gets stuck. To solve this problem, JS usually asynchronously processes time-consuming operations

  • There is asynchrony in JS

    Js has an asynchronous queue in which all time-consuming operations are dumped. When the main thread is idle (synchronous code), the code in the asynchronous queue is executed, which is the EVENTloop in JS.

(2) macro task and micro task

1- Asynchronous operations provided by the macro task running environment setTimeout setInterval setImedia Animareque

Microtasks are asynchronous operations of THE JS language itself promise.then promise.catch

2- After the execution of each round of macro tasks, if there are any micro tasks, the current round of micro tasks will be first. When all the micro tasks are completed, the next macro task cycle will be entered.

3- Code to implement macro and micro task execution sequence

      console.log(1);
      setTimeout(() = > {
        console.log(2);
      }, 0);
      console.log(3);
      setTimeout(() = > {
        console.log(4);
      }, 3);
      var p = new Promise((resolve, reject) = > {
        console.log(5);
        setTimeout(() = > {
          console.log(6);
          resolve();
        }, 1);
      });
      p.then((res) = > {
        console.log(7);
      });
	// => 1 3 5 2 6 7 4
Copy the code

13- Anti-shake and throttling

  • Anti – shake: Definition: When an event is triggered for several times in a period of time, the event is executed only for the last time. If the event is triggered again within the set interval, the timer is cleared and the timer is restarted.

    <button>One click</button>
    Copy the code
    var btn = document.querySelector("button");
    
          // timer global variable
          let timer = null;
    
          btn.onclick = function () {
            console.log(11);
            clearTimeout(timer);
            timer = setTimeout(() = > {
              console.log("Send a request");
            }, 500);
          };
    Copy the code
  • Throttling: Definition: When an event is triggered consecutively for several times in a period of time, the event can be executed only once in each interval.

    <button>One click</button>
    Copy the code
    var btn = document.querySelector("button");
          var flag = true;
          let count = 0;
    
          btn.onclick = function () {
            console.log(count + 1);
            if (flag) {
              flag = false;
              // Throttling is performed once every second
              console.log("Send a request");
    
              setTimeout(() = > {
                flag = true;
              }, 1000); }};Copy the code

New methods for the 14-ES6 array

A summary of forEach(), map(), filter(), reduce(), some(), every() in arrays

  • 1, the forEach ()

    var arr = [1.2.3.4];
    arr.forEach((item,index,arr) = > {
     console.log(item) // result is 1,2,3,4
    })
    //forEach traverses an array of numbers, no return value, no change to the original array, just traversal, often used to register components, directives, etc.
    Copy the code
  • 2, map ()

    var arr = [1.2.3.4];
    arr.map((item,index,arr) = > {
        return item*10 // the new array is 10,20,30,40
    })
    //map iterates through the array and returns a new array without changing the value of the original array.
    Copy the code
  • 3, the filter ()

    var arr = [1.2.3.4];
    arr.filter((item,index,arr) = > {
        return item > 2 // the new array is [3,4]
    })
    //filter returns a new array without changing the value of the original array.
    Copy the code
  • 4, the reduce ()

    var arr = [1.2.3.4];
    arr.reduce((result,item,index,arr) = > {
        console.log(result) // 1 3 6 result is the result of the last calculation
        console.log(item)  / / 2, 3, 4
        console.log(index) / / 1 2 3
        return result+item // The final result is 10
    },initValue)
    //reduce makes the first and last items of the array perform some kind of calculation. It then returns its value and continues the calculation. Returns the final result of the calculation, starting with the second item in the array
    Copy the code
  • 5, some ()

    var arr = [1.2.3.4];
    arr.some((item,index,arr) = > {
        return item > 3 // Result is true
    })
    // If one of the items in the array returns true, the result is true. Do not change the original array
    Copy the code
  • 6, every ()

    var arr = [1.2.3.4];
    arr.every((item,index,arr) = > {
        return item > 1 // The result is false
    })
    // Iterate over each item of the array, return true for each item, and the final result is true. When either item returns false, stop traversal and return false. Do not change the original array
    Copy the code

    The above six methods are ES6 syntax, which is supported only by Internet Explorer 9 or later. However, Babel can be converted to support lower versions of IE. None of the above changes the original array.

    Some and every return true and false. Map and filter return a new array. Reduce makes the front and back of the array perform some kind of calculation that returns the result of the final operation. ForEach has no return value.

15- Garbage collection mechanism

  • Mark clearing algorithm

    This algorithm can be divided into two stages, one is mark and the other is sweep.

    • Mark phase
      • Starting with the root (global) object, each object that can be accessed from the root object is tagged as reachable
    • Sweep phase
      • The heap is traversed linearly from beginning to end and if an object is found unmarked the memory occupied by the object is reclaimed and the identity of the previously marked object is cleared

Defect:

  • Objects that cannot be queried from the root object are cleared

  • Garbage collection may result in a large amount of garbage debris

  • Introducing counting algorithm

    Keep track of how many times each value is applied.

    • When you declare a variable and assign a value of a reference type to that variable, the number of references is 1. If you assign the same value to another variable, the number of references is +1
    • Conversely, if the variable that contains this value takes another value then it is worth referencing -1
    • When the number of references is zero, there is no way to access the value and the next garbage collector will clean up the number of references to zero

Defect:

  • Unable to handle circular references. If two objects are created and reference each other to form a loop. Considering that they have a reference to each other, they will not be recycled

16 – written promise

      var a1 = new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve("A second");
        }, 1000);
      });
      var a2 = new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve("3 seconds");
        }, 3000);
      });
      var a3 = new Promise((resolve, reject) = > {
        setTimeout(() = > {
          reject("5 seconds");
        }, 5000);
      });
      // a1.then((res) => {
      // console.log(res);
      // }).catch((err) => {
      // console.log(err);
      / /});
      // All entries are executed successfully
      // Promise.all([a2, a1, a3])
      // .then((res) => {
      // console.log(res);
      / /})
      // .catch((err) => {
      // console.log(err);
      / /});
      / / racing
      // Promise.race([a3, a2, a1]).then((res) => {
      // console.log(res);
      / /});
      var aa = new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve("This is the result of the execution.");
        }, 1000);
      });
      // aa.then((res) => {
      // console.log(res);
      // return 123;
      / /})
      // .then((res) => {
      // console.log(res);
      // return 456;
      / /})
      // .then((res) => {
      // console.log(res);
      / /});

      // async await
      async function text() {
        const result = await aa;
        console.log(result);
        console.log(1111);
      }
      text();
      // function* aa(){}
Copy the code

17- Deep copy and shallow copy

Consider both base and reference data types

  • Shallow copy: References are simply copied, and operations on each other affect each other
  • Deep copy: redistributing memory in the heap, at different addresses, with the same value, without affecting each other (full copy)
  • In general, the main difference between shallow and deep copying is whether you copy a reference or an instance

Shallow copy method: for object.assgin…

Json. parse stringify (cannot copy function)

lodash

var obj = {
        name: "zhangsan".age: 28.aaa() {},
        child: {
          name: "zhangsanfeng".age: 1.child: { name: "zhangwuji".age: 0,}}};1.Lodash methodlet res1 = _.clone(obj);/ / shallow copy
	let res2 = _.cloneDeep(obj);/ / copy
2.Json. parse stringify (cannot copy functions)// One sentence deep copy
      let cloneObj = JSON.parse(JSON.stringify(obj)); // Methods cannot be copied
3.Object.assign()
	// Shallow copy copies if the property is an object - directly copies the address
	Object.assign(cloneObj, obj); / / shallow copy
4.for
    letcloneObj = { ... obj };/ / shallow copy
        for (let prop in obj) {
          prop; / / the property name
          obj[prop]; / / property values
          console.log(prop, obj[prop]);
          cloneObj[prop] = obj[prop];
        }
5.recursive// Deep copy If property is object - create object - copy property and property value
      function deepClone(obj) {
        let cloneObj = {};
        for (let prop in obj) {
          prop; / / the property name
          obj[prop]; / / property values
          console.log(prop, obj[prop]);
          let value = obj[prop];
          if (typeof value == "object") {
            value; // is an object
            // Create an object like value
            cloneObj[prop] = deepClone(value);
          } else {
            //cloneObj[name] = zhangsancloneObj[prop] = value; }}return cloneObj;
      }
Copy the code

18- Differences between GET and POST

  • Get passes data in a URL of limited length

  • The data passed by POST is larger in the request body

  • Post requests are mainly used to pass large amounts of data for new operations

  • Get, which will be cached in the browser

  • Post is not cached in our browser

  • Get is for getting, post is for sending

  • Post requests are mainly used to pass large amounts of data for new operations

19 – closure

Closures are functions that can read variables inside other functions

In essence, closures are Bridges that connect the inside and outside of a function.

Definition:

  • There’s A function A, and inside A function A returns A function B
  • There’s A variable outside of function A that receives this function B
  • Function B accesses private variables inside function A

Closure implementation:

	  function fmn() {
        var a = 1;
        function test() {
          // console.log(a);
          a++;
          // when a is used in a scope, the parent scope is not found until the global scope
          // Scope chain
          return a;
        }
        return test;
      }
      //res is the test function
      // res->test -> a

      The test execution space uses a, which will not be destroyed
      var res = fmn();
      console.log(res);// =>a=2
      // Make local variables like global variables, cannot be changed arbitrarily, local variables are protected
Copy the code

20- Pros and cons of closures

Why is it called a feature, because every point is a strength and a weakness

  1. Scope space is not destroyed
    • Advantages: Variable pages are not destroyed because they are not destroyed, increasing the lifetime of variables
    • Disadvantages: Because do not destroy, will always take up memory, more later will lead to memory overflow
  2. You can use closures to access variables outside of a function
    • Advantages: Internal data can be accessed from outside the function
    • Disadvantages: References must always be kept, resulting in the function execution stack not being destroyed
  3. Protecting private variables
    • Advantages: you can put some variables in functions without contaminating the whole world
    • Disadvantages: Not very convenient to access using closure functions

21- What is a memory leak

A memory leak is also known as a memory leak"Storage leakage", the dynamic memory allocation function is used to dynamically open space, after the end of use is not released, the result is always occupied by the memory unit. Until the end of the program.// A memory leak is a memory leak.
// Common causes of memory leaks
1, memory leakage caused by singletons2Memory leaks caused by static instances created by non-static inner classes3Example of memory leak caused by Handler: Create static object of anonymous inner class4Memory leak caused by thread5, memory leakage caused by unclosed resourcesCopy the code

22- Those operations could cause a memory leak

  • closure
  • Unexpected global variable (no one knows when it was written so it keeps being referenced)
  • The forgotten timer
  • No clean REFERENCES to DOM elements (previously obtained DOM elements that were later deleted, but references to the element are still in memory)

23- Prototypes and prototype chains

// Prototype: each constructor has a prototype attribute. Prototype holds all the methods used to instantiate an object. The constructor creates an object with a __proto__ attribute pointing to the prototype attribute of the constructor.

// Prototype chain: When we use an object's property or method, we first look in our own memory and use it. If we can't find it, we look in the prototype. The essence of a prototype is an object, and the object has its own prototype. If the prototype does not have this method, it will search in the prototype of the prototype, and the search chain is called the prototype chain.
If Object.prototype does not have this property, return undefind, because object. prototype is null.
Copy the code

24-JS event propagation process

Event capture phase, In target phase, event bubbling phase.

(1) Capture phase: Events flow from the root node to the target node, passing through various DOM nodes on the way, triggering capture events at each node until the target node is reached. (2Target phase: In this phase, events are transmitted to the target node. When the browser finds a listener that has been assigned to the target event, it runs that listener. (3) event bubbling: When the same event handler is set for multiple nested elements, they trigger event bubbling. In an event bubble, the innermost element fires its event first, then the next element in the stack fires it, and so on until the outermost element is reached. If you assign event handlers to all elements, these events will fire in sequence.Copy the code

25- ES6 variable lift is what:

Var/function/let/const/import/class var specifies the scope of a variable to be global or function level. The variable defined by var can be modified. If it is not initialized, undefined will be output without error. A variable defined by const, usually used when requiring a module or defining global constants. Let can only be declared once, and var can be declared multiple times

// About variable promotion:
1Only the declaration itself is promoted, not the assignment operation.2Variables are promoted to the top of their function, not the top of the entire program.3Function declarations are promoted, but function expressions are not.4, function declarations take precedence over normal variable declarations, and function declarations are promoted along with the part of the function definition.5The same variable is declared only once. Others are ignored.Copy the code

26- This points to the problem

//- A normal function call, in which this points to window
//- constructor call, this refers to the instance object
//- Object method call, this refers to the object that the method belongs to
//- Event binding, this refers to the object to which the event is bound
//- Timer function, this points to window
//- arrow function, this points to context
Copy the code

Change the method this points to

/ / three types:
1.call( thisObject, parameter to point to1, the parameter2, the parameter3,...).2.apply(thisObject to which [argument] points1, the parameter2, the parameter3. ] )3.bind(thisObject, parameter to point to1, the parameter2, the parameter3,...).// Same point:
 1./* Change the pointer to this inside a function call. The first argument is the object this points to inside the function
// Different points:
 1.Call starts with the second argument as an argument to the function and is passed as a single argument, not as an array of arguments.2.Apply starts with the second argument as the function's argument, and the second argument is an array that contains all of the function's arguments.3.Bind starts with the second argument as the function argument, andThe /* argument is single pass, */Cannot be passed as an array of arguments and returns the inside of a binding functionthisBind creates a new function that we have to call manuallyCopy the code

27- Page rendering logic

1.The HTML and CSS are parsed separately to generate a DOM tree and a CSSOM tree2.Merge into render tree3.Layout according to render tree4.Finally, GPU is invoked to draw and display on the screenCopy the code

28- Browser cache Strong cache negotiation cache

Caching strategies/* Strong cache: */Instead of sending a request to the server, the resource is read directly from the cache,/* Negotiate cache: */After the cache is invalid, the browser sends a request to the server with the cache ID. The server decides whether to use the cache based on the cache IDCopy the code

29- Promise request encapsulation

export default function ajax(url, data = {}, type = "GET") {
  return new Promise((resolve, reject) = > {
    let promise;
    if (type === "GET") {
      / / get request
      promise = axios.get(url, { params: data }); // This is originally a promise object
    } else {
      promise = axios.post(url, data);
    }
    promise
      .then((response) = > {
        resolve(response.data);
      })
      .catch((error) = > {
        message.error("Request error:" + error.message);
      });
  });
}
Copy the code

30- Check if it is an array

Method one:instanceof:
var arr=[];
console.log(arr instanceof Array) / / return trueMethod 2:constructor:
console.log(arr.constructor == Array); / / return trueMethod 3:Array.isArray()
console.log(Array.isArray(arr)); / / return trueMethod 4:Object.prototype.toString.call()
console.log(Object.prototype.toString.call(arr))  //"[object Array]"
Copy the code

31- The process from entering the url to displaying the page

 1.Your URL2.The DNS3.A TCP connection4.Sending an HTTP request5.The server processes the request6.The server responds to requests7.The browser parses the rendered page8.Connect the end of theCopy the code

What are the asynchronous operations of 32-JS

1.The timer2.event3.AJAX
4.The callback functionCopy the code

33- The difference between Promise and Async

Async A promise object that can return await

1.The function is preceded by the ayNC keyword.2.awaitThe keyword can only be used in functions defined by AYNC.3.asyncThe function implicitly returns a promise whose resolve value is the functionreturnThe value of the.// Second opinion
1. PromiseIs the syntax for handling asynchronous requests in ES6, using.then() for chain calls and.catch() for exceptions.2. async/awaitIs thePromiseUpgrade,asyncUsed to declare that a function is asynchronous,awaitIs to wait for an asynchronous method to complete (awaitaPromiseObject),/* Async /await exceptions can be caught using try/catch syntax. * /(.catch syntax can also be used.)Copy the code

34- Common design patterns

Singleton pattern, observer pattern, composite patternCopy the code

35- Modular development

Modular development: the way documents are organized, managed, and used. That is, splitting a large file into several smaller files that reference and rely on each other's strengths:1.Rendering pages can be accelerated. The loading time of all resources is not accelerated by modularity, but modularity can speed up rendering2.Avoid naming conflicts3.High code reuse4.Clearer thinking and less code couplingCopy the code

36-es and common.js differences

1Es is introduced statically and at compile time/ / asynchronouses6 {export: 'Can print more than one, output as {}'.export default : 'Only one can be exported. It can be exported at the same time as export, but this is not recommended.'Determine foreign output interface, phase, phase generated interface, the module is not the object, the load is not the object, can be loaded separately with an interface (method), the static analysis, dynamic reference, the output is the reference value, the value change, reference is also changed, namely the values in the original module to change the value of load is also changing,thisPoint to theundefined
}
2, common.js is dynamically imported at execution time// Synchronize the import
commonJS { 
	module.exports =  ...   :      'Can only output one, and the ones that follow will overwrite the ones that follow.'.exports. :'Can output more than one'The module is an object, and the object is loaded, and the whole module is loaded, that is, all the interfaces are loaded in. The output is a copy of the value, that is, the change of the value in the original module will not affect the value that has been loaded.thisPoint to the current module}Copy the code

37- For in/for of Difference Return value

In general usefor inTraversal objects,// return key traversal number group returns the subscript
for ofTraversal number group;// Return the value of each itemNot that it can't be usedfor inIterate over the number group, just usefor inAll enumerable properties of an array are iterated over, including its prototype methods, i.efor inIterating over the index (key name) of the array, andfor ofWe iterate over the values of the array elements;for ofIterators provide a way to access the elements of a collection object without exposing the inner details of the object.for inReturns the key of an object or the index of an array or string.for ofJust like forEach returns the value directlyCopy the code

38-XSS attack, CRFS attack

// XSS attack:The attacker injects malicious scripts on the target website to run on the user's browser. Using these malicious scripts, attackers can obtain sensitive user information such as cookies and sessionIDS, thus compromising data security. Defending against XSS attacks:httpOnlyCookie: After the HttpOnly attribute is set in cookie, the JS script cannot read cookie information. Input filtering:1: Detection is entered in the specified format2: Escape HTML, escape quotes, Angle brackets, and slash// CRFS attack:An attack that tricks a user into performing unintended actions on a currently logged Web application. Defense against CSFS attacks: Verification code: Forces the user to interact with the application before completing the final request. Set the tokenCopy the code

39- HTTP common status code

- 200: The server has successfully processed the request. -3xx: indicates redirection. -401: unauthorized, server requests authentication. -404: The server could not find the requested page. -500: An internal error occurred on the server. The request could not be completed. -503: The server is unavailable.Copy the code

What is the difference between forEach and map in 40-JS?

  1. Both can be used to iterate over arrays, forEach returns no value, and map maps and returns a new array.
  2. ForEach allows you to change the value of the original array, whereas Map does not.

42- Object oriented

OOP, object-oriented programming, OBJECT Oriented Design, OOA, object-oriented analysis/* Process-oriented */ // It is specific and process-oriented. To solve a problem, you need to analyze step by step and realize step by step.
/* Object oriented */ // It is modeled, you just abstract out a class, it is a closed box, where you have the data and the solution to the problem. What functions do you need to use directly instead of implementing them step by stepFeatures:// Inherit encapsulation polymorphism
Copy the code

43- Array deduplication

1, use the SET method in ES62, indexOf () method3, using the array sort() method4Make use of the array includes5Using doubleforLoop, reuse splice method for replay (common in ES5), function recursionCopy the code
  • 1. Use the SET method in ES6

        function unique10(arr) {
            //Set data structure, which is similar to an array in that its members have unique values
            return Array.from(new Set(arr)); // Convert a Set structure to an Array using array. from
        }
        console.log(unique10([1.1.2.3.5.3.1.5.6.7.4]));
        // The result is [1, 2, 3, 5, 6, 7, 4]
    Copy the code
  • IndexOf (

        function unique4(arr) {
            var newArr = []
            for (var i = 0; i < arr.length; i++) {
                if (newArr.indexOf(arr[i])===-1) {
                    newArr.push(arr[i])
                }
            }
            return newArr
        }
        console.log(unique4([1.1.2.3.5.3.1.5.6.7.4]));
        // The result is [1, 2, 3, 5, 6, 7, 4]
    Copy the code
  • 3, Use the array sort() method

    // Sort the original array, compare it with the adjacent array, and store it to the new array.
        function unique2(arr) {
            var formArr = arr.sort()
            var newArr=[formArr[0]]
            for (let i = 1; i < formArr.length; i++) {
                if(formArr[i]! ==formArr[i-1]) {
                    newArr.push(formArr[i])
                }
            }
            return newArr
        }
        console.log(unique2([1.1.2.3.5.3.1.5.6.7.4]));
        // the result is [1, 2, 3, 4,5, 6, 7]
    Copy the code
  • 4, use the array includes

        function unique5(arr) {
            var newArr = []
            for (var i = 0; i < arr.length; i++) {
                if(! newArr.includes(arr[i])) { newArr.push(arr[i]) } }return newArr
        }
        console.log(unique5([1.1.2.3.5.3.1.5.6.7.4]));
        // The result is [1, 2, 3, 5, 6, 7, 4]
    Copy the code
  • 5. Use the double for loop, and then use the splice method for reduplication (common in ES5), function recursion

        function unique8(arr) {
            var i,j,len = arr.length;
            for (i = 0; i < len; i++) {
                for (j = i + 1; j < len; j++) {
                    if (arr[i] == arr[j]) {
                        arr.splice(j, 1); len--; j--; }}}return arr;
        }
        console.log(unique8([1.1.2.3.5.3.1.5.6.7.4]));
    Copy the code

    Git git

    // Connect remote repository to local repository (SSH public key association)
    1.git remote add origin [email protected]:ldf-fan/project-team.git 
    // Push the local repository to the master branch of the remote repository
    2.git push -u origin master
    // Download (clone) the remote repository code to the local terminal
    3.Git Clone repository (SSH)// View the branch
    4.git branch
    // Switch to dev branch. If there is no dev branch, create branch and switch to dev branch
    5.git checkout -b dev
    // Check the status.
    6.git status
    // Add all local code (after modification) to the cache
    7.git add .
    // Commit the cached code (contents) to the history area (preferably note the changes made in this commit)
    8.git commit -m "First modification"
    // Switch to the master branch.
    9.git checkout master
    // View all local and remote branches
    10.git branch -a
    // Merge dev branch into current branch (content)
    11.Git merge dev// Delete the local XXX branch
    12.git branch -d xxx
    // First pull the latest content (version) of the remote repository to the current local branch directly merge purposes to ensure that the remote repository is the latest version of the code when the local push to the remote branch (if the same file is modified, there may be conflicts)
    13.git pull
    // Push local code to remote repository
    14.git push
    Copy the code

3. Vue. Js

vue

1- Data bidirectional binding principle

  • Vue two-way data binding is realized through data hijacking combined with publish and subscribe mode, that is, data and view synchronization, data changes, view changes, data changes;
  • Core: For VUE two-way data binding, the core is the Object.defineProperty() method
  • Object.defineproperty () (1) Object.defineProperty(obj, prop, descriptor) Descriptor obj (objects on which attributes are to be defined) prop (properties to be defined or modified) descriptor (2) When we call it, we use the get method, and when we assign the property, we use the set method;

Advantages:

  • Changes made by the user in the view are automatically synchronized to the data model, and changes in the data model are immediately synchronized to the view.

  • No operations related to one-way data binding;

  • In a scenario where forms interact a lot, a lot of business-neutral code is simplified.

Disadvantages:

  • Unable to track local state changes;

Code implementation:

	<div id="app">
      <h1 v-text="num"></h1>
      <p v-text="num"></p>
      <input v-model="num" />
    </div>
Copy the code
    <script>
      var obj = { _num: 0 };
      Object.defineProperty(obj, "num", {
        get() {
          console.log("Get executes");
          return obj._num;
        },
        set(v) {
          console.log("Set executed");
          obj._num = v;
          console.log(obj._num);
          var elems = document.querySelectorAll("*[v-text='num']");
          for (var i = 0; i < elems.length; i++) {
            elems[i].innerHTML = v;
          }
          var els = document.querySelectorAll("*[v-model='num']");
          for (var i = 0; i < els.length; i++) {
            els[i].value = v;
            els[i].oninput = function (e) { obj.num = e.target.value; }; }}}); obj.num; obj.num =100;
    </script>
Copy the code

2 –.onceApplication scenarios

<! Click event will only trigger once -->
<a v-on:click.once="doThis"></a>.stop: equivalent to JavaScript event.stopPropagation() to prevent event bubbles; .prevent: Equivalent to event.preventDefault() in JavaScript, to prevent the preset behavior from being performed (if the event is cancelable, cancel the event without stopping further propagation of the event); .capture: In contrast to the direction of event bubbling, events are captured from the outside in; .self: triggers only events within its own scope, no child elements;Copy the code

3 – handwritten Mvvm

<! -- Above 1 -- Principle of bidirectional data binding -->
Copy the code

4- The difference between MVC and MVVMwww.jianshu.com/p/b0aab1ffa…

MVC: including view view layer, Controller control layer, model data layer. The Controller is responsible for displaying the Model’s data in the View. In other words, the Controller assigns the Model’s data to the View.

**MVVM: ** Includes the View layer, the Model data layer, and the ViewModel layer (instantiated objects).

  • Vue is an MVVM framework that implements two-way data binding, updating the model layer when the view changes and updating the view layer when the model layer changes. In VUE, bidirectional binding technology is used, that is, the changes of the View can change the Model in real time, and the changes of the Model can be updated to the View in real time.

  • The ViewModel connects the View layer with the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic, do not need to manually manipulate DOM, do not need to pay attention to the synchronization of data state. Complex data state maintenance is managed entirely by MVVM.Copy the code

The biggest difference between MVVM and MVC is that it realizes the automatic synchronization of View and Model. That is, when the property of Model changes, we no longer need to manually manipulate Dom elements to change the display of View. Instead, the display of the property corresponding to the View layer will be automatically changed after the property is changed.

MVC and MVVM are not that different. It's all a design idea. Basically, the Controller in MVC morphed into the viewModel in MVVM. MVVM mainly solves the problem that a large number of DOM operations in MVC reduce page rendering performance, slow loading speed and affect user experience. And when the Model changes frequently, developers need to actively update the View.Copy the code

5- What is the virtual DOM?

  • Vdom can be seen as a tree structure that uses JS to simulate the DOM structure and is a layer of abstraction from the real DOM. Can be understood as a simple JS object.

6- What is the function of the key value in Vue?

  • Key is needed to make a unique identification for each node, and Diff algorithm can correctly identify this node.

  • The main purpose is to update the virtual DOM efficiently.

7- Interview questions: The difference between V-if and V-show

A:/* Common: */Can control the display and hiding of elements;/* Difference: */The essence of v-show is to set the display in the CSS to None, to hide, and only compile once. v-ifDynamically add or remove DOM elements to or from the DOM tree if the initial value isfalse, it won't compile. And v -ifConstant destruction and creation costs performance. Summary: If you want to switch nodes frequently, use v-show(switching costs are low and initial overhead is high). If you do not need to switch a node frequently, use V -if(Small initial rendering overhead, large switching overhead).Copy the code

8-Vue.js life cycle

A Vue instance has a complete life cycle, that is, from the beginning of creation, initialization of data, template compilation, Dom mounting, render, update, render (update Dom), destruction, etc., we call this the life cycle of a Vue. Vue instance is the process from creation to destruction.

Each component or instance goes through a complete life cycle consisting of three phases: initialization, running, and destruction. Lifecycle hooks for different phases are triggered during execution.

  • 1.beforeCreate(){}: Data observation and event configuration are called after instance initialization// This is the first lifecycle function encountered indicating that the instance will be fully created and executed
    	// Note that when the beforeCreate life cycle function is executed, the data in data and methods are not initialized
    2.created(){}: called immediately after the instance is created// Instance creation phase, which is the second lifecycle function
    	// This lifecycle phase is used to invoke the interface and initialize the data
        // In Created, data and methods are already initialized
        // If you want to call methods, you can only do it in Created at first
    3.beforeMount(){}: called before the mount begins: the relevant render function is called for the first time// This is the third lifecycle function encountered, indicating that the template has been compiled but not rendered to the page
    	// When beforeMount is executed, the elements in the page are not really replaced, just the previous template strings
    4.mounted(){}: called after the instance is mounted// This is the fourth lifecycle function encountered, indicating that the template in memory has actually been mounted to the browser page, and the user has seen the rendered page
    	// Mounted is the last lifecycle function in the instance creation. When mounted is executed, the instance is fully created
    5.beforeUpdate(){}: beforeUpdate is performed immediately after a component or instance's data changes// Called when data is updated, before the virtual DOM is patched. This is a good place to access the existing DOM before updating, such as manually removing event listeners that have been added
    6.updated(){} :// This hook is called after the virtual DOM is re-rendered and patched due to data changes.
        // When this hook is called, the component DOM is updated, so you can now perform DOM-dependent operations.
    7.beforeDestroy(){} :// called before instance destruction. At this step, the instance is still fully available.
    	// Immediately execute beforeDestroy after calling the $destroy method in some way, usually doing some cleanup here, such as clearing timers, clearing non-instruction-bound events, and so on
    8.destroyed(){} :// called after instance destruction. When this hook is called, all instructions for the Vue instance are unbound, all event listeners are removed, and all subinstances are destroyed.
    Copy the code
  • demo

    	<div id="app">
          <input type="button" @click="msg='nono'" value="Button" />
          <p>{{msg}}</p>
          <button @click="xiaohui">The destruction</button>
        </div>
    Copy the code
          var vm = new Vue({
            el: "#app".data: {
              msg: "ok",},methods: {
              show() {
                console.log("I did it!);
              },
              xiaohui() {
                vm.$destroy();// Completely destroy an instance. Clean up its connections to other instances and unbind all its instructions and event listeners.}},beforeCreate() {
              // This is the first lifecycle function encountered indicating that the instance will be fully created and executed
              console.log(this.msg); //undefined
              this.show(); //this.show is not a method
              // Note that when the beforeCreate life cycle function is executed, the data in data and methods are not initialized
            },
            // Instance creation phase, which is the second lifecycle function
            created() {
              // This lifecycle phase is used to invoke the interface and initialize the data
              // In Created, data and methods are already initialized
              // If you want to call methods, you can only do it in Created at first
              console.log(this.msg);
              this.show();
              console.log(document.querySelector("p").innerHTML);
              this.$nextTick(() = > {
                console.log(document.querySelector("p").innerHTML);
              });
            },
            beforeMount() {
              // This is the third lifecycle function encountered, indicating that the template has been compiled but not rendered to the page
              console.log(document.querySelector("p").innerHTML);
              console.log("msg".this.msg);
              // When beforeMount is executed, the elements in the page are not really replaced, just the previous template strings
            },
            mounted() {
              // This is the fourth lifecycle function encountered, indicating that the template in memory has actually been mounted to the browser page, and the user has seen the rendered page
              console.log("mounted".document.querySelector("p").innerText);
              // Mounted is the last lifecycle function in the instance creation. When mounted is executed, the instance is fully created
            },
            beforeUpdate() {
              // Called when data is updated, before the virtual DOM is patched. This is a good place to access the existing DOM before updating it
              console.log("beforeUpdate".this.msg);
              console.log("mounted".document.querySelector("p").innerText);
            },
            updated() {
              // This hook is called after the virtual DOM is re-rendered and patched due to data changes.
              // When this hook is called, the component DOM is updated, so you can now perform DOM-dependent operations.
              console.log("beforeUpdate".this.msg);
              console.log("mounted".document.querySelector("p").innerText);
            },
            beforeDestroy() {
                // called before instance destruction. At this step, the instance is still fully available.
              console.log("Before destruction.");
            },
            destroyed() {
                // called after instance destruction. When this hook is called, all instructions for the Vue instance are unbound, all event listeners are removed, and all subinstances are destroyed.
              console.log("After destruction"); }});Copy the code

9-vm.$nextTick() solves special effects rendering problems

  • When you modify the value of data and immediately retrieve the dom element value, you cannot retrieve the updated value. You need to use the $nextTick callback to render the modified data value and update it to the DOM element before retrieving it.

10 – component

  • Components have their own data and methods;

  • The data in the component must be a function and have a return value;

  • Components also have their own life cycle;

  • There can only be one root component in a Vue;

  • Note the order in which components are executed;

11- How does a child component change a parent

Note: component information flows can only be one-way 1 > parent/child parameter pass: via property prop: pass data

The parent component passes data down to the child component via props

The parent passes data to the child through props, and the child passes data to the parent through events ($emit);

$parent / $children can also communicate with each other ($parent / $children);

Ref can also access component instances; Provide/inject API; $attrs/$listeners

    <div id="app">
      <p>{{msg}}</p>
      <child
        @func="changemmsg"
        title="I am the title."
        xxx="What is it?"
        :parentmsg="msg"
      ></child>
      <transition @before-enter="" @enter="" :duration="{}"></transition>
    </div>
    <script>
      Vue.component("child", {
        props: ["title"."xxx"."parentmsg"].// props accepts an odd number passed by the parent component
        template: ` < div > < p > this is a four data, the title is {{title}} < / p > < p > {{XXX}} < / p > < p = "changemsg" @ click > parent component passed the MSG - {{parentmsg}} < / p > < / div > `.data() {
          return {};
        },
        methods: {
          changemsg() {
            // this.$emit("func", "I am the child after the parent component modified value ");
            this.$emit("func", {
              str: "Child component ready to modify parent component".msg: "ok"}); ,}}});new Vue({
        el: "#app".data: {
          msg: "I am the MSG of the parent component",},methods: {
          changemmsg(str) {
            console.log(str);
            this.msg = str.str; ,}}});Copy the code

12- Method, Watch, computed

Watch: Supports asynchrony, does not depend on cache, one-to-many, executes if changes occur computed: Does not support asynchrony dependent Cache many-to-one Changes occur only when a dependency changes

13- Route forward parameter transfer mode

Vue provides three basic route parameter transmission modes

Scenario: Click a button on the current page to jump to another page and bring a value there

<div class="examine" @click="insurance(2)">Check the details</div>
Copy the code
  • The first method does not lose page refresh data

    Methods: {insurance(id) {
           // Call $router.push directly to jump with parameters
            this.$router.push({
              path: `/particulars/${id}`})},// The route configuration is as follows:
       {
         path: '/particulars/:id'.name: 'particulars'.component: particulars
       }
    // Add /:id to path to match the path parameter in $router.push. Can be used in a child component to get the value of the passed argument
    // Obtain the following parameters from the page
    this.$route.params.id
    Copy the code
  • Page refresh data is lost in the second method

    The matched route is determined by name in the route attribute, and the parameters are passed through params.

    Methods: {insurance(id) {
           this.$router.push({
              name: 'particulars'.params: {
                id: id
              }
            })
    }
        // Route configuration: Note that :/id cannot be used to pass parameters, because params is already used to carry parameters in components.
     {
         path: '/particulars'.name: 'particulars'.component: particulars
       }
    Copy the code

    Child component: To get the parameters

    this.$route.params.id
    Copy the code
  • The third method uses path to match the route, and then passes the parameters through Query in which case the parameters passed by Query are displayed after the URL, okay? Id =?

    {
         path: '/particulars'.name: 'particulars'.component: particulars
    }
    // Subcomponent: this is how to get parameters
    this.$route.query.id
    Copy the code

Note, in particular, that the parameters in the component are retrievedRouter This is important

14-keep-alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering. Once a component is wrapped with Keepalive, the mouted, created, and other hook functions are called only when the component is first entered and not when it is switched back. If we want to do something with each switch, we need to use the other periodic hook functions, actived and deactived, which are only called when keepalive wraps them.Copy the code

15- VUE performance optimization

1,// Do not use v-for and v-if at the same level. V-for has a higher priority than v-if and executes the loop first.
2,// Js resources used in VUE should be loaded in CDN mode as far as possible to reduce the volume after packaging
3. // Route lazy loading
	{      
  		path: '/'.name: 'home'.component: () = > import('./views/home/index.vue'),      
  		meta: { isShowHead: true}}4,// On-demand import of components, such as element UI Ant Design and other frameworks provide on-demand import, which functions are required to import which components.
5,// ICONS and images are optimized for rationality
	1.Use SVG for small ICONS2.Load small images through Base64 and WebP3.Large images should be loaded in CND mode4.Lazy loading of images, most UI frameworks have lazy loading of images, none can use V-lazy6. // Enabling Gzip is a compression technology. You need to provide a compression package at the front end and enable the compression on the server. The file is compressed on the server and sent to the browser, which decompresses the file and then parses it.
7. // Keep-alive page cache Keep-alive caches the data of the current page to avoid the performance impact of repeated interface calls
	<keep-alive :include="tagsList">
   		<router-view :key="$route.fullPath"></router-view>
	</keep-alive>
8,// Avoid memory leaks
9,// Reduce redundant code from ES6 to ES5
10,// Code level optimization
	(1) Computed and Watch distinguish between usage scenarios (2) v-ifAnd V-show distinguish scenarios V -ifSuitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions. The optimization point here is to reduce the total dom on the page, and I prefer v-ifBecause the dom number is reduced.Copy the code

16-Vue parent component lifecycle call order

  • Loading the rendering process

Parent beforeCreate-> Parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount> Child Mounted -> parent Mounted

  • Child component update process

Parent beforeUpdate-> Child beforeUpdate-> Child updated-> Parent updated

  • Parent component update process

Father father beforeUpdate – > updated

  • Destruction of the process

Parent beforeDestroy-> Child beforeDestroy-> Child destroyed-> Parent destroyed

  • To understand:

Components are called in the order of parent before child, rendering must be completed in the order of child after parent

The destruction of a component is parent before child, and the destruction is completed in the order of child after parent

vue-router

vuex


4. The React

react

1- Determine whether this.setState () is synchronous or asynchronous

It can be synchronous or asynchronous

  • In the case of synthetic events, asynchrony

(1) State changes during synthesis events (2) State changes during the lifecycle

  • In a native event is synchronization

    (1) In the native operation (2)setTimeout is also synchronized

    Batch processing (once the state changes, the React component is rerendered)

2- Controlled and uncontrolled components

Form elements that use state control are controlled components (controlled components are typically for forms)

3- Difference between a function component and a class component

There are two requirements for defining a component: (1) The component name must be capitalized, and (2) the return value of the component must have only one root element

  • Whether a component is declared using a function component or a class component, it must not modify props

  • All React components must be pure functions and do not modify their props

  • React is a single data stream. The parent component changes properties and the child component views are updated

  • Props is passed, state is self

The difference between:

  • Functional components perform better than class components
  • Class components need to be instantiated when used, function components can directly execute the return, to improve performance as far as possible use function components.
  • Function components have no this, no life cycle, no state, use hooks to simulate local state and life cycle functions

4- The react component transmits parameters

  • Parameter transfer between components

    // Use the context context to implement global data sharing by using the context.provider data Provider.
    Copy the code
  • 1. Father passes son

    // Parent passes attributes from the parent component to the child component, which can be received and used directly by the props.Can't change the data in props, the data in props is read-onlyCopy the code
  • 2. The child modifies the father

    // Define a method that is passed to a child component that calls the method to change the value of the parent component
    Copy the code

    Code implementation:

          class App extends Component {
            constructor(props) {
              super(props);
              this.state = {
                count: 10}; } addcount =() = > {
              this.setState({
                count: this.state.count + 1}); };// Define a method that is passed to a child component that calls the method to change the value of the parent component
            changecount = (num) = > {
              this.setState({
                count: num,
              });
            };
            render() {
              const { count } = this.state;
              return (
                <div>
                  <span>{count}</span>
                  <button onClick={this.addcount}>count++</button>
                  <Child
                    name="Zhang"
                    age="20"
                    count={count}
                    changecount={this.changecount}
                  />
                </div>); }}class Child extends Component {
            constructor(props) {
              super(props);
              this.state = {};
            }
            render() {
              return (
                <div>I'm a child component<span>{this.props.name}</span>
                  <span>Age is {this. Props. Age}</span>
                  <span>The value of count is {this.props. Count}</span>
                  <button onClick={()= >This.props. Changecount (1000)}> Modify count in props</button>
                </div>); }}Copy the code

5-refs

Refs provides a way to access DOM nodes or React elements created in the Render method.

  • The class components ref

    ref
      (1) ref="aaa"  
      (2) ref={(span) = >{this.span=span}}  
      (3) this.span = React.createRef()
          <Child ref={this.span} />  // You can call a property or method of a component to get the value of a child component or to execute logic code
    Copy the code

6-React Lifecycle (Class Component)

  • Mount the stage

    Initialization phaseconstructor()// The initialization phase is mainlypropsandstate
    componentWillMount// To mount, this life cycle is executed only once, usually for one-off specified datarender// Start renderingcomponentDidMount// The mount is completerenderAfter that, the life cycle is executed only once, and in this phase it is mainly initiatedajaxRequests, request data, subscribe messages, etcCopy the code
  • In-operation phase

    // The first route props changed
    componentWillReciverProps()// The child component state receives the parameters. The component is going to accept the parameters (the parameters passed), and receives the latest props
    shouldComponentUpdate// This is a valve, should the component update, return true to continue updating, return false to stop updating, not further down, (can do performance optimization)
    componentWillUpdate()// The component will be updated
    render// Component render initialization is performed, as are props or state changes
    componentDidUpdate// The component has been updated
    
    // Route 2 state changed
    useState()// When the component is updated
    shouldComponentUpdate// This is an example of a component that should be updated. If it returns true to continue updating, if it returns false to stop updating, it is not going to continue.
    componentWillUpdate()// The component will be updated
    render// Component rendering
    componentDidUpdate// The component has been updated, (this is where you can get the latest state,props)
    
    // componentWillUpdate()
    force.update()// Force an update
    componentWillUpdate()// The component will be updated
    render// Component rendering
    componentDidUpdate// The component has been updated
    Copy the code
  • Destruction of phase

    componentWillUnMount// During the uninstallation phase, you can cancel the timer and unsubscribe messages, etc
    Copy the code

    Pay attention to the new life cycle after the abandoned componentWillMount componentWIllReceiveProps componentWillUpdate

    16.3After the new life cycle function is getDerviedStateFromProps and getSnapshotBeforeUpdate deleted componentwillreceiverpropsCopy the code

7- What are react-hooks

  • React-hooks are a set of “Hooks” that make function components more powerful and flexible.

What problem was solved?

1.It allows you to write without writingclassIn case of usestateAnd so forthReactFeatures, 2.HookAllows you to reuse state logic without modifying component structureCopy the code

8- React diff principle

- Breaks down the tree structure by hierarchy, comparing only peer elements. - Add a unique key attribute to each unit of the list structure for easy comparison. - React matches only the sameclasscomponent(The inside of thisclassRefers to the component name) - merge operation, callcomponentsetStateWhen it comes to methods,ReactMark it asdirty.At the end of each event loop,ReactCheck all marksdirtycomponentRedraw. - Select subtree render. Developers can override itshouldComponentUpdateTo improvediffPerformance.Copy the code

9- React key functions

Keys are an auxiliary identifier used by React to track which elements in a list were changed, added, or removed. Make the diff algorithm more efficient// During development, we need to ensure that an element's key is unique among its siblings. In the React Diff algorithm, React uses the Key value of an element to determine whether the element is newly created or moved, thus reducing unnecessary element re-rendering. React also relies on keys to determine the relationship between elements and local state, so we should never ignore the importance of keys in conversion functions
Copy the code

10- What is a pure function

1.The same input always returns the same output,2.Without modifying the input value of the function,3.Independent of the state of the external environment.4.No side effects.Copy the code

11- Webpack packs principles for those plug-ins

Packaging principle: Webpack treats the project as a whole. Given a master file, Webpack will start from this master file to find all dependent files in your project, use loader to process them, and finally package them into one or more browser-recognized JS filesCopy the code

10 – JSX syntax

That is, you write HTML tags directly in JS and in JSX syntax if you want to display data on a page you use {} (curly braces)Copy the code

11 – common hooks

// useState,useEffect,useReducer,useContext,useMemo,useCallback,useRef
1.useState
    // useState can set a local state in a component defined by function
    // When the state data changes, the component is re-rendered
2.UseEffect (Side effects) (1Other actions triggered when data changes (2UseEffect takes two arguments. The first argument is a callback function. The second argument is an array.3The contents of the array are dependencies. This callback is executed when the dependency array is changed.4If the dependency array is empty, it is executed only once (5UseEffect The first argument can return onefunctionThis method is executed once when the component is destroyed.useCallback
	(1) receives two parameters. Parameter one is onefunctionArgument 2 is a dependency array (2It can cache methods without reassigning values if the data in the dependent array has not changed (3) Use as much as possible to reduce memory space.useMemo
	(1) You can cache data and return a value that takes two arguments (2) Parameter one is a single parameterfunctionCalculation results (3Argument 2 is a dependency array (4If the dependent array does not change, the value 5 is not reassigned.useRef
	(1) of the current componentdomElement six.useReducer
	(1) to usereduxTo implement state management (2) eachreducerIs afunctionthefunctionAccording to eachactionReturns a new state data (3) if you want to change the datadispatchDistributing aactioneachactionThere is atypeAttributes are used to distinguish betweenreducer7.useContext // contextContext can solve the problem of component parameter passingcontextYou can define global data that can be used by each component, solving the problem of parameter transfer across componentsexport const context = createContext() const {Provider} = context
    <Provider value={{}} > < /Provider>   // valueRepresents the data provider // when used firstimport {UseContext} from 'react'
    import {context} from './Provider'The Provider is a componentconst {} = useContext(context) // Destruct the assignment

Copy the code

12- Custom hooks

13-useEffect

Two parameters

  • The first argument is a function that is a side effect of the first render and subsequent updates.

    This function may have a return value, and if it has a return value, the return value must be a function that is executed when the component is destroyed.
    / / copy componentDidMount
    useEffect(() = > {
              console.log("UseEffect here for componnetDidMount");
              // componentWillUnmount is executed when the component is destroyed
              return () = > {
                console.log("componentWillUnmount"); }; } []);Copy the code
  • The second argument, optional, is an array containing some of the side effect properties used in the first function. Used to optimize useEffect

    If you use this optimization, make sure that the array contains any values in the outer scope that change over time and are used by effect. Otherwise, your code will refer to old values from previous renderings. If you want to run Effect and clean it up only once (when loading and unloading), you can pass the empty array ([]) as the second argument. This tells React that your effect doesn't depend on any values from props or state, so it never needs to be run again.// If the dependency changes, it will be executed
            useEffect(() = > {
              console.log("Count here simulates componentDidUpdate.");
            }, [count]);
            useEffect(() = > {
              console.log("Name here simulates componentDidUpdate");
            }, [name]);
            useEffect(() = > {
              console.log("Name or count has changed.");
            }, [count, name]);
    Copy the code

Integrated class component componentDidMount, componentDidUpdate, componentWillUnMount hook function ability, and the code is more concise.

14- What is the difference between useCallback and useMemo

UseMemo caches data useCallback Caches methods Defining a method without useCallback will cause memory waste// Both useMemo and useCallback are executed when the component is first rendered, and again when its dependent variable changesAnd both hooks return cached values,// useMemo returns cached variables, useCallback returns cached functions
Copy the code

15- What are higher-order components/higher-order functions

// Advanced component concept: passing a component as an argument to a component (method) returns a component with a new property
// Higher-order functions: pass a function function as an argument, wrapper returns a new function, such as array map,reduce methods, etc
// React is a single data stream. Data is passed from properties to subcomponents. Properties are read-only and cannot be changed
Copy the code

16- What happens after calling setState?

// After calling setState, the parameters passed in are merged with the current state. This is the synchronization process between the real DOM and the virtual DOM.
// React efficiently builds a new DOM tree based on the latest data state and then rerenders the page.
// When React builds a new DOM tree, local rendering is performed based on the differences between the old and new DOM, updating as needed.
Copy the code

17- What are the synthesized events in React?

// Composite events are objects that act as cross-browser wrappers around browser native events.
// They combine the behavior of different browsers into one API.
// This is done to ensure that events display consistent properties across browsers.
Copy the code

18-memo

React. memo is a higher-order component// It is used to optimize the performance of components without re-rendering components if their properties do not changeMemo is afunctionReturns a new component that takes a component as an argumentmemoThe modified components have new features, and the component is not re-executed when the property data does not change. The benefit is performance optimizationCopy the code

19- React Key functions

React Performance Optimization

react-router-dom

1- Common route hooks

1.useHistory(push,replace,go) 
2.UseParams (get id parameters such as /detail/:id)3.useLocation(search,state,pathname)
Copy the code

redux

The flow chart of story

1 – redux understanding

/ /? Redux is an independent third-party library for managing state. It is not a React plugin, but is commonly used in React projects
/ / role? : Centralized management of application state (write/read)Development: Works with react-redux, redux-thunk, etcCopy the code

2 – story related API

Redux contains createStore(), applyMiddleware(), combineReducers() store objects: getState(), dispatch(), subscribe() react-redux:<Provider store={store}>: Store Connect (state => ({XXX: state.xxx}), {actionCreator1, actionCreator2})(UI component): The resulting container component is responsible for passing tag properties to the UI component. The general property value is taken from state, and the dispatch action is performed inside the function propertyCopy the code

3-REdux Core Concepts (3)

// action: The default is object (synchronous action), {type: 'xxx'.data: value}, which needs to be generated by the corresponding actionCreator. Its value can also be a function (asynchronous action), which requires redux-thunk// reducerDepending on the old state and the specified action, returning a new state cannot modify the old state// storeThe core management object of REdux is internally managed by state and reducer. Methods provided are: getState(), dispatch(action), subscribe(listener).Copy the code

Vue vs. React