The third round of job hunting - JS interview questions from shallow to deep

foreword

I will have an interview tomorrow, and I will organize js in the evening. Hope to win! ! !

CSS interviews can be moved: the second round of job hunting - one article is enough to challenge the difficult points of CSS


Theory

1.js single thread

Essential difference: Process is the basic unit of operating system resource allocation, while thread is the basic unit of processor task scheduling and execution.

Containment relationship: A process has at least one thread, and a thread is a part of a process, so a thread is also called a lightweight process or a lightweight process.

The reason why JS is single-threaded is mainly related to the purpose of JS. JS mainly realizes the interaction between the browser and the user, and operates the DOM.

If JS is designed to be multi-threaded, if one thread wants to modify a DOM element and another thread wants to delete the DOM element, then the browser does not know what to do. In order to avoid complicated situations, JS is single-threaded .

2.js data type

There are seven data types in js:
Number, String, Undefined, Symbol, Boolean, Null, Object.

Among them, Symbol is a new basic data type introduced in ES6, which is used to represent a unique value.

Values ​​of the three primitive types—numeric, string, and Boolean—under certain conditions are automatically converted to objects, which are “wrapper objects” of primitive types.

3.js memory leak

Understanding: Useless memory is still occupied and cannot be released or returned. In severe cases, useless memory will increase, causing the entire system to freeze or even crash.

Causes:
unexpected global variables;
when DOM elements are emptied, there are still references;
closures;
forgotten timers.

Optimization:
Global variables are declared before use;
avoid excessive use of closures;
pay attention to clearing timers and event listeners.

4.js macro task and micro task (event loop mechanism)

A synchronous task refers to a task that is queued for execution on the main thread. Only when the previous task is completed can the next task be executed.

Asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". Only when the main thread task is executed, the tasks in the "task queue" will enter the main thread for execution.

Asynchronous tasks are divided into macro tasks and micro tasks. The microtask queue of the same scope is executed prior to the macrotask queue. As long as there are tasks in the microtask queue, the macrotask queue will only wait for the microtask queue to complete before executing.

Common macro tasks: settimeout setInterval script (the outermost script tag);

Common microtasks: promise (async await).

5.js scope and scope chain

Scope:
Before ES6, js only had global scope and function scope. After ES6, js has block-level scope. The range in which variables and functions can be used is called scope

Global scope:

在任何地方都能访问到的对象

local scope:

又称函数作用域,仅供函数内部访问

Variable scope:

分为全局变量和局部变量。其中,全局变量使在全局作用下的变量,局部变量是在局部作用域下的变量。

Note that if the variable that is not declared inside the function but is assigned is also a global variable, this requires special memory:
insert image description here
Global variables are stored in memory and will be destroyed only when the browser is closed, which takes up more memory resources; while local variables will be destroyed after the program is executed, which saves internal resources. So we prefer to use local variables.

Scope chain: The internal function accesses the variables of the external function, and adopts a chain search method to determine which value to take. This structure is called a scope chain.

For details, see: One article to understand the scope and scope chain of js

6.js closure

A function is a closure if it accesses scope variables at or above the function's parent.

        //闭包指有权访问另一个函数作用域中变量的函数
        //fun这个函数作用域,访问了fn中的局部变量num,则产生闭包
        function fn() {
    
    
            var num = 10;
            function fun() {
    
    
                console.log(num);
            }
            fun();
        };
        fn(); 

The function of the closure: access the internal variables of the function and keep them in memory.

The conditions that the closure satisfies:
access the scope, function nesting, and being called in the scope.

The characteristics of the closure:
the local variables of the parent and above functions accessed by the closure function (such as the local variable i in the example) will always exist in memory and will not be recycled by the garbage collection mechanism of JS.
Closure functions implement access to variables inside other functions. (Variables inside the function cannot be accessed externally, and closures achieve access through this workaround.)

Disadvantage: memory leak.

7. New additions in ES6

let, const join; destructuring assignment, template string; arrow function; expansion operator;

In the class class, the prototype chain is no longer used to implement inheritance like ES5, but the concept of Class is introduced;

Promise is a new asynchronous solution that solves hell callbacks and is more flexible than traditional callbacks; async and await can also be used in combination with Promise (to improve code readability);

Symbol is a primitive type. Symbol is generated by calling the symbol function, which receives an optional name parameter, and the symbol returned by the function is unique;

The Proxy proxy uses the proxy (Proxy) to monitor the operation of the object, and then can do some corresponding things;

Set is a data collection similar to an array, unordered, fast insertion and deletion, no repeated elements, fast search speed;

Map is a data structure similar to objects. The difference from objects is that its key can be of any type, but objects can only use string and symbol types, and the storage association of Map is stronger;

8. Prototypes and prototype chains

Prototype:
A prototype is an object template that defines some public properties and methods for object instances.

Prototype chain:
insert image description here

8. Deep copy

Shallow copy: only copy
Deep copy: deep copy copies multiple layers, each level of data will be copied

9. js anti-shake and throttling

Anti-shake: When the event is triggered, a timer is executed, and the timer is successfully triggered after the timer expires. This prevents the event from being fired too often.

Features: Trigger frequently, but only execute once;

Throttling: Reduce the trigger frequency of events and selectively execute some events. Triggered every once in a while.

10. this in js points to

1. This in the script points to window;

2. The this in the arrow function points to the this of the upper and lower environment;

3. The this of the object property points to the this of the context outside the object; the this in the object method (ordinary function) points to the current object (whoever executes the method, this points to whom)

11. Change the call, apply, and bind pointed to by this

call: When fn.call is called, the this point in fn will be modified to the first parameter passed in thisArg; the following parameters will be passed to fn, and the function fn will be executed immediately.

apply: modify this point, and execute fn immediately. The difference is that the form of parameter passing is different. apply accepts two parameters. The first parameter is the this object to point to, and the second parameter is an array. The elements in the array will be expanded and passed to fn as the parameter of fn.

bind: The function of fn.bind is to only modify the point of this, but not execute fn immediately; it will return a fn after modifying the point of this. It needs to be called to execute: bind(thisArg, arg1, arg2, arg3, ...)(). The parameter passing of bind is the same as that of call.

12. Event stream

Event flow refers to the order in which events are received from a page. The event flow model is divided into two parts: bubbling event flow and capture event flow.

Capture: The capture phase refers to the process of finding the target element. This process of finding is from the largest document object to HTML, then to body, until the target element.

target stage;

Bubbling: After the execution of the event of the target element ends, it goes from the target element to its parent element. . . The process from body, html to document is the bubbling stage.

Stop event bubbling:
e.stopPropagation();

.stop and .prevent in vue can be realized

13. DOM and BOM

DOM: document object type, methods and interfaces for web pages;
BOM: browser object type, methods and interfaces for handling browser interaction.

14. The difference between let, const and var

var: There is variable promotion, you can declare it first and then use it. A variable can be declared multiple times, and the subsequent declarations will overwrite the previous declarations. Var can also be a global variable. Let and const are both local; let: There is no variable
promotion , Before let declares a variable, the variable cannot use
const: const to declare a read-only variable. After the declaration, the value cannot be changed (the address of the reference type cannot be changed, but the value can be changed); the compound type can change the attribute.

15. The difference between ordinary functions and arrow functions

The appearance is different;
ordinary functions can have names, but arrow functions must be anonymous functions;
ordinary functions can be used in constructors, but arrow functions cannot
; Points to the object it was defined in;
arrow functions do not have a prototype and super.

16. Problems with callback functions and callback functions

Pass the function as a parameter to another function, and when this function is needed, call back to run() this function.

The callback function is an executable code segment, which is passed to other codes as a parameter, and its function is to call this (callback function) code conveniently when needed. (passed as a parameter to another function, this function as a parameter is the callback function)

Understanding: A function can be passed as a parameter to another function.

Features: It will not be executed immediately, and it is a closure.

Problem: this points to the nearest function caller, and the arrow function can solve the problem that the this of the callback function does not have a name.

The reason for the callback function: JavaScript is an event-driven language. This means that JavaScript will not stop the current execution because it is waiting for a response, but will continue to execute while listening to other events

17. Cross-domain browser

Why block cross-domain: same-origin policy (to solve network security issues);

Solve cross-domain: jsonp, cross-domain resource sharing, request header.

18. The role of new

First create an empty object, then point this to the object, and this this inherits the prototype of the object.

Properties and methods are also added to this object.

19.Json

Json is a data exchange format.

Convert JSON string to JSON object

let obj = JSON.parse(str);

JSON 对象转换为 JSON 字符串

let obj = JSON.stringify(str);

20. HTTP common status codes

200: normal;
4xx: indicates client error, such as 400, request syntax error, 403 is generally cross-domain; 404 is generally resource not found;
5xx: server error, error occurred in executing the request.

21.promise

es6 introduces to solve the hell callback problem, which can be called in a chain and is very flexible.

There are three states: pedding, resolve (success), and reject (failure).

Promise.finally() The finally method is used to execute the function inside the Promise regardless of the state of the Promise.

Promise.all()和promise.race():

The role of Promise.all() is to receive a group of asynchronous tasks, and then execute the tasks in parallel, and then execute the callback after all tasks are executed. Promise.all() passes in
a set of Promise arrays, and returns only when all the Promise states are successful. Success, as long as there is a failure, return the failed Promise status

The function of Promise.race() is to receive a group of asynchronous tasks, and then execute the tasks in parallel. Only the first completed task is kept, and other tasks will still be executed, but the execution results will be discarded. Promise.race() is passed
in An array of Promises, the returned result is determined by the result of the first fulfilled Promise object

Promise itself is synchronous, while then and catch are asynchronous.

22.Ajax

1. 创建 ajax 对象
const ajax = new XMLHttpRequest();

2. 创建 ajax 请求 (设置请求的方法和请求地址)  open
ajax.open('get', 'http://localhost:8080/server?a=100&b=200');

3. 发送请求  send
ajax.send();

4. 处理服务器端返回的结果  onreadystatechange事件  
   readystate:五个值 0 1 2 3 4,为4的时候代表数据已经接收完成
   status:状态码  200 为成功
   if(ajax.readystate === 4 && ajax.status >= 200 && ajax.status < 300) {
    
    
   		表示成功,可以写相应的逻辑了
   }

23.for-in和for-of

Both are used to iterate through the array.

Guess you like

Origin blog.csdn.net/zxdznyy/article/details/131507509