[Direct collection] 100 front-end JavaScript interview questions (Part 1)

1. Explain what closure is?

  • Closure: It is a function that can read the internal variables of the outer function.

  • Closures need to meet three conditions:

    • Access the scope;

    • Function nesting;

    • Called outside the scope.

  • Advantages: Variables can be reused without causing variable pollution.

  • Disadvantages: Can cause memory leaks

  • Notes on using closures:

    • Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page, and may lead to memory leaks in IE. The solution is to delete all unused local variables before exiting the function.

    • Closures change the values ​​of variables inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.

2. Explain prototype and prototype chain?

prototype

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

prototype chain

The inheritance relationship between objects is a pointing chain formed by pointing to the parent class object through the prototype of the constructor until it points to the Object object.

In layman's terms: the prototype chain is the historical record of the creation process of the prototype object.

Note: In JavaScript, all objects have a __proto__ attribute that points to the prototype of the object.

3. Tell me about some of the things you are familiar with in ES6?

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

  • Async and await use async/await, and with promise, you can handle asynchronous processes by writing code that looks like synchronization, improving the simplicity and readability of the code. async is used to declare that a function is asynchronous, and await is used to wait for an asynchronous method. Execution completed

  • Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions (callback functions and events)

  • Symbol is a basic type. Symbol is generated by calling the symbol function, which receives an optional name parameter. The symbol returned by this function is unique.

  • Proxy agent uses proxy (Proxy) to listen to the operation of the object, and then can do some corresponding things

  • Set is a data collection similar to an array. It is unordered, has fast insertion and deletion speeds, no duplicate elements, and fast search speeds.

  • Map is an object-like data structure. The difference from an object is that its key can be of any type, but objects can only use string and symbol types. Map's storage relevance is stronger

  • The generator function can block the execution of the function. By passing parameters, new values ​​can be passed into the function to continue execution. It can be used to turn asynchronous into blocking synchronization.

4. How to sort arrays?

  • Bubble Sort:

   for(var i=0;i<arr.length-1;i++){
           for(var j=0;j<arr.length-i-1;j++){
               if(arr[j]>arr[j+1]){
                  var temp=arr[j];
                  arr[j]=arr[j+1];
                  arr[j+1]=temp;
              }
          }
       if(arr[j]===arr[j-1]) i++;
      }
  • Select sort:

for(var i=0;i<arr.length;i++){
          was min=i;
           for(var j=i+1;j<arr.length;j++){
               if(arr[j]<arr[min]) min=j;
          }
           if(min!==i){
              var temp=arr[i];
              arr[i]=arr[min];
              arr[min]=temp;
          }
       if(arr[i]===arr[i+1])i++;
}
  • Quick sort:

function quickSort(arr) {
  if (arr.length <= 1) return arr;
  var centerIndex = ~~(arr.length / 2);
  var left = [];
  var right = [];
   for (var i = 0; i < arr.length; i++) {
       if (i === centerIndex) continue;
       if (arr[i] < arr[centerIndex]) left.push(arr[i]);
       else right.push(arr[i]);
      }
      return quickSort(left).concat(arr[centerIndex], quickSort(right));
  }

5. What is event loop (EventLoop)?

A program structure for waiting for and sending messages and events.

  • 1. All tasks are executed on the main thread, forming an execution stack.

  • 2. The main thread finds that there is an asynchronous task. If it is a microtask, it will put it in the message queue of the microtask. If it is a macrotask, it will put it in the message queue of the macrotask.

  • 3. All synchronization tasks in the execution stack are completed.

  • 4. Execute the microtask queue, and then execute the macrotask queue.

  • 5. Polling step 4.

6. Some APIs for arrays, which ones can change the original array, and which ones cannot?

  • How to change the original array:

shift()
unshift()
pop()
push()
reverse()
sort()
splice()
  • Method without changing the original array:

concat()
every()
filter()
forEach()
indexOf()
join()
lastIndexOf()
map()
some()
every()
slice()
reduce()
reduceRight()
flat()
flatMap()
find()

7. What is the difference between for loop and forEach?

  • 1.For loops can use break to jump out of the loop, but forEach cannot.

  • 2. The for loop can control the starting point of the loop (the number initialized by i determines the starting point of the loop), and forEach can only start from index 0 by default.

  • 3. It supports modifying the index (modifying i) during the for loop process, but forEach cannot do this (the underlying control index increases automatically and cannot control it).

8. Deep and shallow copy?

  • Deep copy:

function cloneObject(source, target) {
     if (target === undefined) {
       if (Node.prototype.isPrototypeOf(source)) {
        target = document.createElement(source.nodeName);
        target.style = source.style.cssText;
      } else if (source.constructor === Uint8Array) {
        target = new source.constructor(Array.from(source));
      } else if (source.constructor === Date || source.constructor === RegExp || source.constructor === Set || source
        .constructor === Map) {
        target = new source.constructor(source);
      } else if (source.constructor === Function) {
        var arg = source.toString().match(/\((.*?)\)/)[1];
        var content = source.toString().replace(/\n|\r/g, "").match(/\{(.*)\}/)[1];
        target = new Function(arg, content)
      } else {
        target = new source.constructor();
      }
    }
    var names = Object.getOwnPropertyNames(source).concat(Object.getOwnPropertySymbols(source));
     for (var i = 0; i < names.length; i++) {
       if (names[i] === "constructor") {
        Object.defineProperty(target, "constructor", {
          value: source.constructor
        });
        continue;
      }
      var desc = Object.getOwnPropertyDescriptor(source, names[i]);
       if ((typeof desc.value === "object" && desc.value !== null) || typeof desc.value === "function") {
        var o = cloneObject(desc.value)
        Object.defineProperty(target, names[i], {
          value: o,
          enumerable: desc.enumerable,
          writable: desc.writable,
          configurable: desc.configurable
        })
      } else {
        Object.defineProperty(target, names[i], desc);
      }
    }
    return target;
  }
  • Shallow copy:

   1. Object.assign(target object, source object)
   2、
  where obj1={}
   for(var key in obj){
      obj1[key]=obj[key]
  }
   3、obj1={...obj};

9. What is the composition of url?

http:/https: protocol
www.baidu.com domain name
:8080 port
/sf/vsearch path
?wd=Baidu hot search query (optional)
#a=1&b=2 Hash value (optional)                        

10. Common cross-domain methods?

  • JSONP: JSONP is a technology that uses external link scripts and has no cross-origin restrictions to implement cross-origin requests.

  • CORS: cors: cross-domain resource sharing, is a technology that enables cross-origin request data. This is one of the solutions to the cross-origin problem. Also a wide range of solutions.

  • Forward proxy first builds its own proxy server

    • 1. The user sends a request to his own proxy server

    • 2. Your own proxy server sends a request to the server

    • 3. The server returns the data to its own proxy server

    • 4. Your own proxy server returns the data to the user

  • reverse proxy

    • 1. The user sends a request to the server (what is accessed is actually a reverse proxy server, but the user does not know it)

    • 2. The reverse proxy server sends the request to the real server

    • 3. The real server returns the data to the reverse proxy server

    • 4. The reverse proxy server returns the data to the user

  • via postMassage,

11. What are the usage scenarios of Promise?

  • Scenario 1: Obtain file information.

  • Scenario 2: Cooperate with AJAX to obtain information

  • Scenario 3: Solve callback hell and implement serial task queue.

  • Scenario 4: Asynchronous process of local operation in node

12. What is the difference between let, const and var?

picture

13. Understanding this, what are three ways to change this?

  • 1. In any case, this written directly in the script is window.

  • 2. This in the function in non-strict mode: this points to window, in strict mode: this points to undefined.

  • 3. Thisthis of the arrow function all points to this of the context outside the arrow function.

  • 4. This in the this object attribute in the object points to this in the this object method (ordinary function) in the context outside the object, pointing to the current object (whoever executes the method, this points to)

  • 5. This points to the callback function

    • 1). The setTimeout and setInterval callback functions will point to window regardless of whether they are in strict mode. 

    • 2) By executing the current callback function within the function, in non-strict mode: this points to window, in strict mode: this points to undefined.

    • 3) This in the recursive function in non-strict mode: this points to window, in strict mode: this points to undefined.

    • 4) When using arguments0 to execute a function, this points to arguments.

    • 5) The callback function in the event, this points to the event listening object (e.currentTarget);

  • 6. The point of this when the call, apply, and bind methods are executed.

    • If parameters are passed to call, apply, or bind, and the first parameter passed is not null or undefined, what does this point to?

    • If the first parameter passed in is null or undefined, it points to window in non-strict mode.  

  • 7. The pointer of this in the ES6 class

    • This in the constructor points to the new instance object generated by the current class of the instance      

    • In the instantiation method in the class, this points to who executes the method, and who this points to      

    • This in a static method in a class executes the class or the constructor of the class      

    • When the arrow method is instantiated in a class, this still points to the instance object instantiated by the current class.

  • 8. The pointer of this in the prototype object of ES5

    • Function name.call(this,....) Whoever writes this refers to whoever is writing it.

    • Function name.apply(this,[parameter 1, parameter 2,...]) Whoever writes this refers to whoever is written.

    • Function name. bind (this,1,2,3) Whoever writes this refers to whoever writes this.

    • In the prototype method, this points to the instantiated object that instantiates the current constructor (whoever executes the method, this points to);

    • Three ways to change the point of this  

14. What is the difference between cookie, localStorage and sessionStorage?

Storage method function and characteristics Storage quantity and size

  • cookie

Storage method
To store user information, obtaining data requires establishing a connection with the server.
Stored in a path, the upper path cannot access the lower path cookie, and the lower path cookie can access the upper path cookie.
Function and characteristics

The data that can be stored is limited and depends on the server. Data that does not require the server should be stored in cookies as much as possible to avoid affecting page performance.

Expiration time can be set.

The storage quantity and size should be controlled within 4095B, ​​and excess data will be ignored.
IE6 or lower versions can store up to 20 cookies;
IE7 and above
There can be up to 50 versions;
Firefox has 50 more;
Chrome and Safari do not have hard restrictions.

The biggest feature of cookies is that they can be passed between the page and the server, and are automatically passed when sending or receiving data.
localStorage
Store client information without requesting the server.

Data is saved permanently unless the user manually clears the client cache.

Developers can encapsulate a method and set the expiration time. About 5M, the storage space of each browser is different.

You can deposit and withdraw anywhere

easy to use
sessionStorage

Store client information without requesting the server.

The data is saved in the current session. The data will not be cleared when the page is refreshed. The data will be invalid when the session is ended (close the browser, close the page, and jump to the page).

About 5M, the storage space of each browser is different.

Data in different windows on the same page will not be shared

15. What do you do from entering the URL to opening the page?

  • Enter URL

  • Access hosts resolution. If there is no resolution, access DNS resolution.

  • TCP handshake

  • HTTP request

  • HTTP response return data

  • The browser parses and renders the page

16. What is the process of native ajax?

  Create xhr
  var xhr=new XMLHTTPRequest()
  Listen for communication status change events
  xhr.addEventListener("readystatechange",readyStateChangeHandler);
  Method is divided into get post put delete etc.
  Async asynchronous synchronization
  name and password are the username and password
  xhr.open(Method,URL,Async,name,password)
  Send content to server
  xhr.send(content)

   function readyStateChangeHandler(e){
    When the status is 4 and the response header is success 200,
      if(xhr.readyState===4 && xhr.status===200){
        Print the returned message
        console.log(xhr.response)
      }
  }

17. How to implement inheritance?

  • For JavaScript, inheritance has two main points:

    • Reuse code in parent constructor

    • Reusing code in the parent prototype The first way to reuse code in the parent constructor is to call the parent constructor and bind this to the child constructor.

  • The first method: reuse the code in the parent prototype, we only need to change the prototype chain. Point the proto attribute of the child constructor's prototype object to the parent constructor's prototype object.

  • The second implementation uses the new operator instead of directly using the proto attribute to change the prototype chain.

  • The third implementation uses an empty constructor as an intermediary function so that properties in the constructor are not mixed into the prototype.

function A(x,y){
this.x = x
this.y = y
}
A.prototype.run = function(){}
// Parasitic inheritance is used together
function B(x,y){
A.call(this,x,y) // Borrowing inheritance
}
B.prototype = new A() // Prototype inheritance
//Combined inheritance
Function.prototype.extends = function(superClass){
 function F(){}
F.prototype = superClass.prototype
 if(superClass.prototype.constructor !== superClass){
  Object.defineProperty(superClass.prototype,'constructor',{value:superClass})
}
let proto = this.prototype
this.prototype = new F()
let names = Reflect.ownKeys(proto)
 for(let i = 0; i < names.length;i++){
  let desc = Object.getOwnPropertyDescriptor(proto,names[i])
  Object.defineProperty(this.prototypr,name[i],desc)
}
this.prototype.super = function(arg){
  superClass.apply(this,arg)
}
this.prototype.supers = superClass.prototype
}
  • The fourth implementation extends the inheritance of es6 classes.

18. What is the difference between null and undefined?

  • null is an object representing "none" (null object pointer), which is 0 when converted to a numerical value;

  • undefined is a primitive value representing "none", which is NaN when converted to a numerical value. expand:

  • null means "no object", that is, there should be no value there. Typical usage is:

    • As a parameter of a function, it means that the parameter of the function is not an object.

    • As the end point of the object's prototype chain.

  • undefined means "missing value", that is, there should be a value here, but it has not been defined. Typical usage is:

    • When a variable is declared but not assigned a value, it is equal to undefined.

    • When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined.

    • The object has no assigned properties, and the value of this property is undefined.

    • When a function does not return a value, it returns undefined by default.

19. Function throttling and anti-shake?

  • Throttle

Throttling means that when an event is triggered, in order to prevent the event from being triggered continuously and frequently, a timer is set to achieve the effect of only triggering once within an event. It will not be triggered again within the current event. After the current event ends, it will be triggered again. It is effective only when triggered.
function thro(cb,wait){
let timeOut
return function(){
   if(timeOut) return
  timeOut = setTimeout(function(){
    cb()
    clearTimeout(timeOut)
    timeOut = null
  },wait)
}
}
  • Anti-shake

Anti-shake means that when an event is triggered, in order to prevent frequent triggering of the event, a timer is set so that it is not processed during the frequent triggering period and is processed only after the last continuous triggering is completed.
function debounce(cb,wait){
let timer
return function(){
  clearTimeout(timer)
  timer = setTimeout(()=>cb(),wait)
}
}

20. What is Promise?

Promise is a solution for asynchronous programming: syntactically, promise is an object from which messages for asynchronous operations can be obtained;
 
In essence, it is a promise, a promise that it will give you a result after a period of time.
 
Promise has three states: pending (waiting state), fulfilled (successful state), rejected (failed state); once the state changes, it will not change again. After a promise instance is created, it will be executed immediately

Promises are used to solve two problems:

Callback Hell, the code is difficult to maintain. Often the output of the first function is the input of the second function.

Promise can support multiple concurrent requests and obtain data in concurrent requests.

This promise can solve the asynchronous problem. It cannot be said that promise is asynchronous.

21. What is the difference between ordinary functions and arrow functions?

The difference between ordinary functions and arrow functions:

  • 1. The arrow function does not have a prototype. The arrow function does not have its own this. It inherits the this of the outer code block.

  • 2. It cannot be used as a constructor, which means that the new command cannot be used, otherwise an error will be reported.

  • 3. You cannot use the arguments object, which does not exist in the function body. If you want to use it, you can use the rest parameter instead.

  • 4. The yield command cannot be used, so arrow functions cannot be used as generator functions.

  • 5. Because there is no this, you cannot use call, bind, or apply to change the direction of this.

22. What are the design patterns? Let’s talk about each one?

There are 23 design patterns in total, and 6 of them are introduced that are widely used.

  • Publish-subscribe model: This design model can greatly reduce the coupling between program modules and facilitate more flexible expansion and maintenance.

  • Mediator pattern: The observer pattern manages the many-to-many relationship between objects by maintaining a bunch of lists. The mediator pattern maintains the one-to-many relationship through a unified interface, and the communicators do not need to know the relationship between each other. You just need to agree on the API.

  • Proxy pattern: Provides a proxy for other objects to control access to this object. The proxy pattern enables proxy objects to control references to specific objects. A proxy can be almost any object: a file, a resource, an object in memory, or something difficult to copy.

  • Singleton mode: Ensure that a class has only one instance and provide a global access point to access it (calling a class will return the same instance at any time).

  • Factory pattern: The factory pattern defines an interface for creating objects. This interface determines which class to instantiate by subclasses. This pattern defers instantiation of a class to subclasses. Subclasses can override interface methods to specify their own object types when creating

  • Decorator pattern: The decorator pattern can dynamically add responsibilities (methods or properties) to an object during program running without changing the object itself. Decorators are a lighter and more flexible approach than inheritance.

23. What are the differences and uses of Promsie and async/await?

the difference:

  • 1) There is an async keyword in front of the function. The await keyword can only be used within functions defined by async. The async function will implicitly return a promise, and the resolve value of the promise is the value of the function return.

  • 2) Point 1 implies that we cannot use await in outer code because it is not inside the async function. use:

    • 1. async and await are used in pairs, and await exists inside async. Otherwise, an error will be reported.

    • 2.await means waiting for a promise to return here before executing it next.

    • 3. What follows await should be a promise object, (it doesn’t have to be, if not, there is no point in what follows...)

24. Let’s talk about the garbage collection mechanism?  

Garbage collection is a dynamic storage management technology that automatically releases "garbage" (objects that are no longer referenced by the program) and implements automatic resource recycling according to a specific garbage collection algorithm. Two mechanisms for recycling

  • 1. Mark clearing (make-and-sweep)

  • 2. Reference counting The garbage collector will be executed periodically at fixed intervals.

25. Array deduplication?

  • The first:

for(var i=0;i<arr.length;i++){
for(var j=i+1;j<arr.length;){
if(arr[i]===arr[j]) arr.splice(j,1);
else j++; // core
}
}
  • The second type:

var arr1=[];
xt: for(var i=0;i<arr.length;i++){
for(var j=0;j<arr1.length;j++){
if(arr1[j]===arr[i]) continue xt;
}
arr1.push(arr[i]);
}
  • The third type:

var arr1=[];
for(var i=0;i<arr.length;i++){
if(arr1.indexOf(arr[i])<0) arr1.push(arr[i])
}
  • The fourth type:

var arr1=[];
for(var i=0;i<arr.length;i++){
if(!(~arr1.indexOf(arr[i]))) arr1.push(arr[i])
}
  • The fifth type:

var arr1=[];
for(var i=0;i<arr.length;i++){
if(!arr1.includes(arr[i])) arr1.push(arr[i])
}
  • Sixth type:

arr=[1,2,3,1,2,3,1,2,3]
new Set(arr);

26. Determine whether the object is empty?

  • The first

Use JSON.stringify() to convert the object to a json string;
JSON.stringify(obj) === '{}'
  • The second kind

Use a for...in loop to traverse all enumerable attributes of the object except Symbol. When the object has attributes, it returns false, otherwise it returns
true。
const obj = {}
function isObjectEmpty(obj){
for(var key in obj){
return false
}
return true
}
console.log(isObjectEmpty(obj))
  • The third kind

The Object.getOwnPropertyNames() method will return the property names of all enumerable and non-enumerable properties of the object (excluding Symbol
attributes). Then it is judged whether the length of the returned array is zero. If it is zero, it is an empty object.
Object.getOwnPropertyNames(obj).length === 0
  • The fourth kind

Object.keys() is a new object method in ES5. This method returns an array containing the specified object’s own enumerable properties (not
Contains inherited and Symbol properties). With this method, you only need to determine whether the length of the returned array is zero. If it is zero, it is an empty object.

27. How to find the two largest values ​​in an array using one loop?

var arr=[1,4,10,11,11,2,5,7,2,3,4];
var [max,second]=arr[0]>arr[1] ? [arr[0],arr[1]] : [arr[1],arr[0]];
 for(var i=2;i<arr.length;i++){
   if(arr[i]>max){
     second=max;
     max=arr[i];
  }else if(arr[i]<=max && arr[i]>second){
     second=arr[i];
  }
}

28. new is the process of an object?

  • 1. Open up a heap memory and create an empty object

  • 2. Execute the constructor to construct this empty object

  • 3. Add proto attribute to this empty object

29. Why can’t you use new for arrow functions?  

Because the arrow function does not have a prototype or its own this pointer and cannot use arguments.

30. How to copy an array?

  • The for loop copies one by one;

var arr1=[];
 for(var i=0;i<arr.length;i++){
   if(i in arr) arr1[i]=arr[i]
}
  • ...Way

  var arr1=[...arr];
  • slice method

var arr1=arr.slice();
  • concat method

var arr1=arr.concat();
  • map method

var arr1=arr.map(item=>item);
  • reduce

var arr1=arr.reduce((v,t)=>v.push(t),[])

For more exciting front-end videos, please search "Qianfeng Education" on Station B 

Qianfeng front-end teacher Xixiya’s HTML+CSS tutorial, a must-see video for getting started with zero-based web front-end development

Supongo que te gusta

Origin blog.csdn.net/GUDUzhongliang/article/details/132974166
Recomendado
Clasificación