1. The way to determine the JS type

  • Type = ‘string’,’number’,’ Boolean ‘,’undefined’,’symbol’; Check that both arrays and objects are ‘object’

  • The instanceof principle is whether the constructor’s prototype property appears anywhere in the object’s prototype chain

  • Object. The prototype. ToString. Call () used to determine the browser built-in objects, for all the basic data types can judge, even if is null, and undefined

  • Array.isarray () is used to check whether it is an Array

2. String manipulation functions

  • ToString () – Any type of data can be converted to a string.

  • Concat () – Combines two or more characters of text to return a new string.

  • IndexOf () – Returns the index at the first occurrence of a substring in a string. If there is no match, -1 is returned.

  • CharAt () – Returns a character at the specified position.

  • LastIndexOf () – Returns the index that appears at the end of a substring in the string, or -1 if there is no match.

  • Match () – Checks whether a string matches a regular expression.

  • The substr() function – begins interception at the start position and ends at the maximum length of the string intercepted by the second argument.

  • Substring () – Returns a substring of the string. The incoming arguments are the start and end positions.

  • Slice () – Extracts a portion of the string and returns a new string.

  • Replace () – Finds the string that matches a regular expression, and replaces the matching string with the new string.

  • Search () – Performs a regular expression match lookup. Returns the matched index in the string if the search succeeds. Otherwise -1 is returned.

  • Split () – Makes a string an array of strings by splitting the string into substrings.

  • Length – Returns the length of the string, which is the number of characters it contains.

  • ToLowerCase () – converts the entire string toLowerCase.

  • ToUpperCase () – converts the entire string toUpperCase.

3.Array properties and methods

  • Includes () – Returns a Boolean value when a match is found. Undefined and NaN are not recognized.

  • Concat () joins two or more arrays and returns the result.

  • Join () puts all the elements of the array into a single string. Elements are separated by the specified delimiter.

  • Pop () removes and returns the last element of the array.

  • Shift () removes and returns the first element of the array

  • Push () adds one or more elements to the end of the array and returns the new length.

  • Unshift () adds one or more elements to the beginning of the array and returns the new length.

  • Reverse () reverses the order of elements in an array.

  • Slice () returns the selected element from an existing array

  • Sort () sorts the elements of an array

  • Splice () removes elements and adds new elements to the array.

  • ToSource () returns the source code for this object.

  • ToString () converts an array to a string and returns the result.

  • ToLocaleString () converts the array to a local array and returns the result.

  • ValueOf () returns the original valueOf an array object

4. Closure concept? The advantages and disadvantages?

A closure is a function that reads variables inside other functions.

Advantages:

  • Avoid contamination of global variables

  • Want a variable to be permanently stored in memory (cache variable)

Disadvantages:

  • Memory leaks (consumption)

  • Resident memory to increase memory usage

5. Shallow copy and deep copy

Shallow copy

  • Object.assign()

  • Array.prototype.slice()

  • Extended operators…

Deep copy

  • JSON.parse(JSON.stringify())

  • Recursive function

function cloneObject(obj) {
  var newObj = {} // If it is not a reference type, return it directly
  if (typeofobj ! = ='object' && !obj) {
    return obj
  }
  // If it is a reference type, traverse the property
  else {
    for (var attr in obj) {
      // If an attribute is still a reference type, call recursively
      newObj[attr] = cloneObject(obj[attr])
    }
  }
  return newObj
}
Copy the code

6. Array deduplication method

The Set of ES6

let arr = [1.1.2.3.4.5.5.6]
let arr2 = [...new Set(arr)]
Copy the code

reduce()

let arr = [1.1.2.3.4.5.5.6]
let arr2 = arr.reduce(function (ar, cur) {
  if(! arr.includes(cur)) { arr.push(cur) }return arr
}, [])
Copy the code

filter()

// There is a problem with this method: [1,'1'] is treated as the same element, and the final input is [1].
let arr = [1.1.2.3.4.5.5.6]
let arr2 = arr.filter(function (item, index) {
  The indexOf() method returns the first occurrence of a specified string value in a string
  return arr.indexOf(item) === index
})
Copy the code

7. What are the stages of DOM events? Talk about the understanding of event agency

It is divided into three stages: capture stage – target stage – bubbling stage

The event broker simply means that the event is not directly bound to an element, but to the element’s parent element. When the event is triggered (for example, ‘click’), the conditional statement (for example, ‘alert(e.target.innerhtml)’) is executed.

Benefits :(1) more concise code; (2) Save memory overhead

8. What is cross-domain? What are the workarounds for requesting resources across domains?

Because of the browser’s same-origin policy, any protocol, domain name, or port that sends the url request is different from the current page address. There are cross-domain cases:

  • Network protocols are different, for example, HTTP to access HTTPS.

  • For example, port 80 accesses port 8080.

  • Domain names vary, such as Qianduanblog.com visit Baidu.com.

  • Subdomains vary, such as abc.qianduanblog.com visit def.qianduanblog.com.

  • Domain name and corresponding IP address, for example, www.a.com to visit 20.205.28.90.

The solution

  • Porxy agent

  • CORS

  • Disadvantages of JSONP: Post requests cannot be sent in this way (here), and it is not easy to determine whether a JSONP request has failed, as most framework implementations rely on timeouts.

9. Talk about the garbage collection mechanism and memory management

Definition and usage :Garbage Collection, the execution environment is responsible for managing the memory used during code execution.

How it works: The garbage collector periodically (periodically) finds variables that are no longer in use and frees their memory. However, this process is not real-time because it is expensive, so the garbage collector executes it periodically at regular intervals.

Garbage collection strategy: tag cleanup (more common) and reference counting.

  • Mark clearance:

    Definition and usage: mark a variable as “in” when it enters the environment, and “out” when it leaves the environment. At some point, the garbage collector filters out variables in the environment, as well as variables referenced by environment variables, leaving variables that are considered ready for collection.

    So far, JS implementations of Internet Explorer, Firefox, Opera, Chrome, and Safari have all used a marked sweep garbage collection strategy or similar strategies, with different garbage collection intervals.

  • Reference count:

    Definition and usage: Reference counting keeps track of how many times each value is referenced.

    Basic principle: is the number of references to a variable, is referenced once plus 1, when the reference count is 0, is considered to be ready to recycle the object.

10. Memory leaks

  • A memory leak is when a computer has less and less memory available, mainly because a program cannot release memory that is no longer being used.

  • Unintentional global variables, loops, timers, callbacks can trigger memory leaks

11. What is the difference between undefined and null

  • Null means “no object”, meaning there should be no value

  • Undefined means “missing value”, that is, there should be a value here, but it is not defined yet

12. Introduce JavaScript archetypes, prototype chains, and their features

All objects in JavaScript are inherited from their prototype objects. The prototype Object itself is also an Object, and it also has its own prototype Object. In this way, a structure similar to a linked list is formed, which is the prototype chain. The end point of all prototype chains is the prototype attribute of Object function. Prototype points to a prototype object that also has a prototype, but its prototype is null, and null has no prototype

13. How does avaScript implement inheritance

  • Prototype chain inheritance
function Animal() {}
Animal.prototype.name = 'cat'
Animal.prototype.age = 1
Animal.prototype.say = function () {
  console.log('hello')}var cat = new Animal()

cat.name // cat
cat.age / / 1
cat.say() // hello
Copy the code
  • Tectonic inheritance
function Animal() {
  this.species = 'animals'
}
function Cat(name, age) {
  Animal.call(this)
  this.name = name
  this.age = age
}

var cat = new Cat('doug'.2)

cat.name / / doug
cat.age / / 2
cat.species / / animals
Copy the code
  • Combination of inheritance
function Animal() {
  this.species = 'animals'
}

function Cat(name) {
  Animal.call(this)
  this.name = name
}

Cat.prototype = new Animal() // Rewrite the prototype
Cat.prototype.constructor = Cat
Copy the code
  • Extends Inheritance ES6 adds a new inheritance method. The extends keyword is used to implement inheritance
class Animal {}

class Cat extends Animal {
  constructor() {
    super()}}Copy the code

14. What exactly does the new operator do

  • Creates an empty object, and the this variable references the object and inherits the prototype of the function

  • Properties and methods are added to the object referenced by this

  • The newly created object is referred to by this and implicitly returns this

15. Bubble sort

The first kind of

var arr = [89.12.8.14.23.45.9.15.33]
function bubble_sort(arr) {
  var len = arr.length
  if (arr.length == 1) {
    return
  }
  for (var i = 0; i < len; i++) {
    for (var j = 0; j < len - 1; j++) {
      // If the former value is greater than the latter value, then switch places
      if (arr[j] > arr[j + 1]) {
        var temp = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = temp
      }
    }
  }
  return arr
}
// Test the code
bubble_sort(arr)
//log [8, 9, 12, 14, 15, 23, 33, 45, 89]
Copy the code

The second,

function quickSort(arr) {
  // If the array <=1, it returns directly
  if (arr.length <= 1) {
    return arr
  }
  var pivotIndex = Math.floor(arr.length / 2)
  // Find the benchmark and delete it from the original array
  var pivot = arr.splice(pivotIndex, 1) [0]
  // Define left and right arrays
  var left = []
  var right = []

  // Smaller than the baseline is placed left, larger than the baseline is placed right
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] <= pivot) {
      left.push(arr[i])
    } else {
      right.push(arr[i])
    }
  }
  / / recursion
  return quickSort(left).concat([pivot], quickSort(right))
}
Copy the code

The third kind of

function selectionSort(array) {
  var length = array.length,
    i,
    j,
    minIndex,
    minValue,
    temp
  for (i = 0; i < length - 1; i++) {
    minIndex = i
    minValue = array[minIndex]
    for (j = i + 1; j < length; j++) {
      if (array[j] < minValue) {
        minIndex = j
        minValue = array[minIndex]
      }
    }
    // Switch places
    temp = array[i]
    array[i] = minValue
    array[minIndex] = temp
  }
  return array
}
Copy the code

Is javascript a weakly typed language

JavaScript is a literal scripting language that is dynamically typed, weakly typed, and prototype-based. Its interpreter is called JavaScript engine, as part of the browser, widely used in client-side scripting language, was first used in HTML web pages, to add dynamic functionality to HTML pages.

Strong typing language:

  • A language that enforces data type definitions. That is, once a variable is assigned a data type, it will remain that data type forever unless cast. For example, if you define an integer variable a, it is impossible for the program to treat a as a string. Strongly typed languages are type-safe languages.

Weak type definition language:

  • Languages in which data types can be ignored. In contrast to strongly typed languages, a variable can be assigned values of different data types.

  • Strong typing languages may be slightly slower than weak typing languages, but the rigor that comes with strong typing languages can effectively prevent many errors.

17. Difference between arrow function and ordinary function

  • The arrow function does not have its own this; it inherits this from the outer code block.

  • Should not be used as a constructor, that is, the new command should not be used, otherwise an error will be reported.

  • You cannot use the Arguments object, which does not exist in the function body. If you do, use the REST argument instead.

  • Yield cannot be used, so arrow functions cannot be used as Generator functions.

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

18. Call,apply and bind

There is no difference in function between them. They both change the direction of this. The main difference lies in the implementation form of the method and the difference in parameter passing. Both the Call and apply methods are executed immediately after the call. The bind call returns the original function and requires a second call to undo the line

  • The difference between writing:

Call (object ask,arg1,arg2….)

Apply (object, [arg1,arg2… )

Var ss= function.bind (object,arg1,arg2,….)

19. Briefly explain your understanding of HTTP and HTTPS

  • HTTP is a hypertext transfer protocol. The data transmitted is unencrypted, that is, displayed on the surface. It is the most widely used network protocol on the Internet. The HTTP port number is generally 80.

  • HTTPS is a secure SSL encrypted transport protocol. To put it simply, HTTPS is a secure version of HTTP. The data transmitted is encrypted through SSL. Compared with HTTP, HTTPS is more secure. However, the cost is relatively high, especially the higher the level of THE REQUIRED CA certificate, the higher the cost (the more powerful the CA certificate, the higher the cost). The HTTPS port number is 443.

  • HTTP and HTTPS each have their own advantages and disadvantages, HTTP cost less, not high security; HTTPS costs a little more, but is more secure;

20. Synchronous and asynchronous

  • Synchronization is when all operations are completed and the result is returned to the user. That is, after the database is written, the user experience is not good for the corresponding user.

  • Asynchronous, do not wait for all operations to be completed, the corresponding user request. That is, first corresponding to the user request, and then slowly to write the database, user experience is better.

21. What about JS data types?

  • String Number Boolean null undefined Symbol bigint

  • Reference type: Object Date function RegExp Array

22. Tell me your understanding of functional programming.

Functional programming is a programming paradigm, which can be understood as the use of functions to encapsulate the operation process, by combining various functions to calculate the result. The biggest difference between functional and imperative programming is that functional programming is concerned with the mapping of data, while imperative programming is concerned with the steps to solve the problem.

23. The understanding of function Currization?

Is the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the remaining arguments and returns the result.

24. Why is corrification needed?

  • Multiple parameters are converted into a cascade of single parameter functions to achieve the purpose of dynamic parameter determination.

  • When certain parameters are uncertain, you can keep a stub. Once the remaining parameters are determined, you can call the remaining parameters from the stub.

25.TCP’s three-way handshake and four-way wave

  • Three-way handshake

1. The client initiates the SYN

2. The server receives and returns a SYN from the ACK client

3. After receiving the SYN and ACK from the server, the client sends the ACK to the server. After receiving the ACK, the server establishes a connection

Client -> SYN -> Server

Server -> SYN/ACK -> Client

Client -> ACK -> Server

  • Four times to wave

1. The client sends the FIN to the server

2. The server sends an ACK to the client

3. The server sends the FIN to the client

4. After receiving the ACK, the client sends the ACK to the server. The server shuts down and the client shuts down after 2MSL

Client -> FIN -> Server

Server -> ACK -> Client

Server -> FIN -> Client

Client -> ACK -> Server -> CLOSED

Client -> 2MSL time -> CLOSED

26. Do you know HTTP cache policy?

  • Strong cache

 I do not send a request to the server. I directly read resources from the cache. In the Network option of the Chrome console, the request returns a status code of 200 and Size indicates from Disk cache or from Memory cache. Strong caching can be implemented by setting two HTTP headers: Expires and cache-Control.

  • Negotiate the cache

Negotiation cache is a process in which the browser sends a request to the server with the cache ID after the cache is invalid, and the server decides whether to use the cache based on the cache ID. The process is as follows: 1. 2. The negotiation cache is invalid. 200 and the request result are returned

27. What happens when you go from URL input to page presentation?

DNS resolution: Resolves a domain name into an IP address

TCP connection: TCP three-way handshake

Sending an HTTP request

The server processes the request and returns HTTP packets

The browser parses the rendered page

Disconnect: TCP wave four times

28. Browser rendering mechanisms

Parse HTML, generate DOM tree, parse CSS, generate CSSOM tree

Combine DOM Tree and CSSOM Tree to generate Render Tree

Layout(backflow): According to the generated rendering tree, backflow (Layout), get the geometry information of nodes (position, size)

Painting(repainting): Get absolute pixels of nodes based on the rendered tree and geometry information from backflow

Display: Send the pixel to the GPU and Display it on the page.

29. Implementation principles of nine cross-domain methods

The JSONP principle takes advantage of the fact that script tags have no cross-domain limitations, allowing web pages to get JSON data dynamically generated from other sources. JSONP requests must be supported by the other party’s server.

CORS requires both browser and backend support. Internet Explorer 8 and 9 need to be implemented through XDomainRequest.

Access-control-allow-origin enables CORS.

PostMessage allows scripts from different sources to communicate asynchronously in a limited manner, enabling cross-text file, multi-window, cross-domain messaging.

Websocket Websocket is a persistent HTML5 protocol that implements full-duplex communication between browser and server, as well as a cross-domain solution.

The Node middleware proxy (twice across domain) implementation principle: The same origin policy is the standard that browsers need to follow, and the same origin policy is not required if the server requests to the server.

Nginx reverse proxy implementation principle is similar to Node middleware proxy, you need to build a relay Nginx server, used to forward requests.

The window.name + iframe window.name attribute is unique in that the name value persists across different pages (and even different domain names) and can support very long name values (2MB).

Location. hash + iframe: a.html wants to communicate with C.HTML across domains, via the middle page B.HTML. Three pages, different fields use iframe location.hash to transfer values, the same fields directly js access to communicate.