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

1. Explain what is a closure?

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

  • Closures need to meet three conditions:

    • access scope;

    • function nesting;

    • Called outside the scope.

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

  • Disadvantage: can cause memory leak

  • Points to note when using closures:

    • Because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause performance problems of the web page, and may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function.

    • The closure will change the value of the variable inside the parent function outside the parent function. So, if you use the parent function as an object (object), the closure as its public method (Public Method), and the internal variable as its private property (private value), then 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 methods for object instances.

prototype chain

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

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

Note: In javascript, all objects have a __proto__ attribute pointing to the object's prototype (prototype).

3. Tell me about some of the content 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, await Use async/await, with promise, you can write synchronous code to handle asynchronous processes, improve code simplicity and readability 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 primitive type. Symbol is generated by calling the symbol function, which accepts an optional name parameter, and the symbol returned by this function is unique

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

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

  • Map is a data structure similar to an object. The difference from an object is that its key can be of any type, but an object can only use string and symbol types, and the storage of Map is more relevant.

  • The generator function can block the execution of the function. By passing parameters, a new value can be passed into the function to continue execution. It can be used to change asynchronous into blocking synchronous

4. How to sort the array?

  • 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 and sending messages and events.

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

  • 2. If the main thread finds an asynchronous task, if it is a microtask, put it in the message queue of the microtask, and if it is a macrotask, put it in the message queue of the macrotask.

  • 3. All synchronization tasks of the execution stack are executed.

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

  • 5. Polling step 4.

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

  • How to change the original array:

shift()
unshift()
pop()
push()
reverse()
sort()
splice()
  • A method that does not change 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. The for loop 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. During the for loop process, it is supported to modify the index (modify i), but forEach cannot do it (the underlying control index is self-incrementing, and it cannot be controlled).

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 chain scripts without cross-origin restrictions to implement cross-origin requests.

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

  • The forward proxy first builds a proxy server of its own

    • 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 (the access 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

  • By postMassage,

11. What are the usage scenarios of Promise?

  • Scenario 1: Get file information.

  • Scenario 2: Get information with AJAX

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

  • Scenario 4: Asynchronous process for local operations in node

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

Statement variable hoisting temporary dead zone repeat statement initial value

scope

was

allow does not exist allow unnecessary

non-block level

let not allowed exist not allowed unnecessary block level
const not allowed exist not allowed need block level

13. Understanding of this, three ways to change this?

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

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

  • 3. The thisthis of the arrow function points to the this of the context outside the arrow function

  • 4. The this object property in the object points to the this in the this object method (ordinary function) of the context outside the object, pointing to the current object (whoever executes the method, this points to who)

  • 5. The this point of the callback function

    • 1), setTimeout, setInterval callback function will point to the window no matter whether it is in strict mode or not. 

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

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

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

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

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

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

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

  • 7. The point 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 this points to who      

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

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

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

    • The function name.call (this,....) refers to whoever writes this.

    • Function name.apply(this,[parameter 1, parameter 2,...]) This refers to whomever is written.

    • Function name. bind (this,1,2,3) This refers to whomever is written.

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

    • 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 and obtain data, a connection to the server is required.
Stored by path, the upper layer path cannot access the lower layer path cookie, but the lower layer path cookie can access the upper layer path cookie
Function and characteristics

The data that can be stored is limited and depends on the server. Data that does not need to request the server should not be stored in cookies as much as possible, so as not to affect page performance.

Expiration time can be set.

The storage quantity and size control the cookie within 4095B, ​​and the excess data will be ignored.
IE6 or lower versions store up to 20 cookies;
IE7 and above
There can be up to 50 versions;
50 more for Firefox;
Chrome and Safari don't do hard limits.

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

The data is stored permanently unless the user manually clears the client cache.

Developers can encapsulate a method by themselves 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, and the data will not be cleared when the page is refreshed, and the data becomes invalid when the session ends (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 did 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 returns data

  • The browser parses and renders the page

16. The process of native ajax?

  create xhr
  var xhr=new XMLHTTPRequest()
  Listen for communication state change events
  xhr.addEventListener("readystatechange",readyStateChangeHandler);
  Method is divided into get post put delete and so on
  Async asynchronous synchronization
  name and password are 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 successful 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 the code in the parent constructor

    • Reusing the code in the parent prototype The first way to reuse the code in the parent constructor, we can consider calling the parent constructor and binding this to the child constructor.

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

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

  • The third implementation uses an empty constructor as an intermediary function, so that the properties in the constructor will not be 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) // borrow inheritance
}
B.prototype = new A() // prototype inheritance
// composite 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 type implements the inheritance extends of es6 class.

18. What is the difference between null and undefined?

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

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

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

    • As a parameter of a function, indicates 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 yet. 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 property, and the value of this property is undefined.

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

19. Function throttling and anti-shake?

  • throttling

Throttling means that when an event is triggered, in order to prevent continuous and frequent triggering of the event, a timer is set to achieve an effect that only triggers once in a period of events, and will not be triggered again in the current event. trigger is valid.
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 trigger events, a timer is set to achieve a frequent trigger period without processing, and only after the last continuous trigger is over.
function debounce(cb,wait){
let timer
return function(){
  clearTimeout(timer)
  timer = setTimeout(()=>cb(),wait)
}
}

20. What is Promise?

Promise is a solution to asynchronous programming: syntactically, a promise is an object from which messages of asynchronous operations can be obtained;
 
In essence, it is 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. Once the promise instance is created, it will execute 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 get data in concurrent requests

This promise can solve the asynchronous problem, but 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 has no prototype (prototype), the arrow function does not have its own this, and inherits the this of the outer code block.

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

  • 3. The arguments object cannot be used, 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 the arrow function cannot be used as a Generator (generator) function.

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

22. What are the design patterns, and talk about them separately?

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

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

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

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

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

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

  • Decorator mode: The decorator mode can dynamically add responsibilities (methods or properties) to an object during program execution without changing the object itself. Compared with inheritance, decorators are a more portable and flexible approach.

23. What is the difference and usage between Promsie and async/await?

the difference:

  • 1) There is an additional async keyword in front of the function. The await keyword can only be used within functions defined by async. The async function implicitly returns a promise whose reosolve value is the value of the function return.

  • 2) Point 1 implies that we cannot use await in the 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, and then execute it next.

    • 3. await should be followed by a promise object, (or not, if not, it doesn’t make much sense…)

24. 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 the function of automatic resource recovery according to a specific garbage collection algorithm. Two mechanisms for recycling

  • 1. Make-and-sweep

  • 2. Reference counting The garbage collector will be executed periodically at fixed time 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])
}
  • The sixth type:

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

26. Judgment object is empty?

  • The first

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

Use the for...in loop to traverse all enumerable properties of the object except Symbol, and return false when the object has properties, otherwise return
true。
const obj = {}
function isObjectEmpty(obj){
for(var key in obj){
return false
}
return true
}
console.log(isObjectEmpty(obj))
  • third

The Object.getOwnPropertyNames() method returns the property names of all enumerable and non-enumerable properties of the object (excluding Symbol
attribute) array. Then judge whether the length of the returned array is zero, if it is zero, it is an empty object.
Object.getOwnPropertyNames(obj).length === 0
  • fourth

Object.keys() is a new object method in ES5, which returns an array containing the enumerable properties of the specified object (not
with inherited and Symbol properties). With this method, you only need to judge whether the length of the returned array is zero, and if it is zero, it is an empty object.

27. How to use a loop to find the two largest values ​​​​in the array?

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. The process of new 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 the arrow function use new?  

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

30. How to realize the copy of the 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),[])

Continue to the next article (Part 2)

https://blog.csdn.net/shi15926lei/article/details/132107907?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/shi15926lei/article/details/132107848