1. This section describes the basic data types of JS.

There are six basic datatypes: Undefined, Null, Boolean, Number, String, and Symbol, which represents unique and immutable datatypes. I think its main purpose is to solve the problem of possible global variable conflicts.Copy the code

2. How many types of values does JavaScript have? Can you draw their memory map?

Knowledge points involved:

Stack: primitive data type (Undefined, Null, Boolean, Number, String) Stack: reference data type (object, array, function) The difference between the two types is that they are stored in different locations. Primitive data types are directly stored in simple data segments in the stack, occupying small space and fixed size. They are frequently used data, so they are stored in the stack. Reference data types Objects stored in the heap take up large space and are of variable size. If stored in the stack, it will affect the performance of the program; The reference data type stores a pointer on the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack, and then retrieves the address from the heap.Copy the code

Answer:

Js can be divided into two types of values, one is basic data type, and one is complex data type. Basic data type.... (See 1) Complex data types refer to the Object type. All other data types, such as Array and Date, can be understood as subclasses of Object. The main difference between the two types is where they are stored. Values for basic data types are stored directly on the stack, while values for complex data types are stored in the heap and retrieved by using the corresponding pointer stored on the stack.Copy the code

See how Many Types of values do JavaScript Have? How many types of values does JavaScript have? Can you draw a memory map of them?

3. What is a heap? What is a stack? What are the differences and connections between them?

The concepts of heap and stack exist in data structures and operating system memory. In the data structure, the access mode of data in the stack is first in last out. The heap is a priority queue and is sorted by priority, which can be specified by size. A complete binary tree is an implementation of a heap. In an operating system, memory is divided into stack areas and heap areas. The stack area memory is automatically allocated and released by the compiler to store function parameter values, local variable values and so on. It operates like a stack in a data structure. Heap memory is usually allocated and freed by the programmer. If the programmer does not free heap memory, it may be reclaimed by the garbage collection mechanism at the end of the program.Copy the code

For more information, see: What is a heap? What is a stack? What are the differences and connections between them?

4. What is the internal attribute [[Class]]?

All objects (such as arrays) whose Typeof returns "object" contain an internal attribute [[Class]] (we can think of this as an internal Class, rather than a Class in the traditional object-oriented sense). This property cannot be accessed directly, usually by the Object. The prototype. The toString ().. To look at it. For example: the Object prototype. ToString. Call ([1, 2, 3]); // "[object Array]" Object.prototype.toString.call( /regex-literal/i ); // "[object RegExp]"Copy the code

5. What built-in objects does JS have?

Knowledge points involved:

Global objects, or standard built-in objects, are not to be confused with "global objects". When I say global objects, I mean objects in the global scope. Other objects in the global scope can be created by the user's script or provided by the host program. Class (1) value properties of standard built-in objects. These global properties return a simple value that has no properties or methods of its own. Such as Infinity, NaN, undefined, null literal (2) function properties, the global function can be called directly, do not need to specify the object when the call, the result will be directly returned to the caller after execution. Such as eval(), parseFloat(), parseInt(), etc. (3) Basic objects, which are the basis for defining or using other objects. Basic objects include generic objects, function objects, and error objects. For example, Object, Function, Boolean, Symbol, Error, etc. (4) number and date objects used to represent numbers, dates, and objects that perform mathematical calculations. Examples are Number, Math, Date (5) strings, objects that represent and manipulate strings. For example, String, RegExp (6) indexable collection objects, which represent collections of data sorted by index value, including arrays and type arrays, and objects with array like structures. Array (7), for example, uses collection objects that use keys when storing data, and supports iterating over elements in the order they are inserted. For example, Map, Set, WeakMap, WeakSet (8) vector Set, data in SIMD vector Set will be organized into a data sequence. For example, SIMD, etc. (9) structured data, these objects are used to represent and manipulate structured buffer data, or data encoded using JSON. (10) Controls abstract objects such as Promise, Generator, etc. (11) reflects internationalization such as Reflect, Proxy, etc. (12) Adds ECMAScript objects to support multilingual processing. Such as Intl, intl.collator, etc. (13) WebAssembly (14) Others such as argumentsCopy the code

Answer:

The built-in object in JS mainly refers to some global value attributes, functions and constructors used to instantiate other objects that exist in the global scope before the program is executed. In general, we often use the global variable value NaN, undefined, global functions such as parseInt(), parseFloat() used to instantiate Object construction functions such as Date, Object, etc., and provide mathematical calculation of the single built-in Object such as Math Object.Copy the code

For details, please refer to “Classification of standard built-in objects” and “Summary of all JS built-in object properties and methods”.

6. The difference between undefined and undeclared?

A variable declared in scope but not yet assigned is undefined. In contrast, variables that have not been declared in scope are undeclared. ReferenceError: b is not defined However, we can use typeof's security precautions to avoid errors because Typeof returns "undefined" for undeclared (or not defined) variables.Copy the code

7. Null vs. undefined

First, Undefined and Null are both basic datatypes, and each of these basic datatypes has only one value, namely Undefined and Null. Undefined means undefined, and null means empty objects. Undefined is returned when a variable is declared but not yet defined. Null is used to initialize variables that may return objects. Undefined is not a reserved word in JS, which means we can use undefined as a variable name, which is very dangerous and can affect our judgment of undefined. But there are ways to get a safe undefined value, such as void 0. Null typing returns "object" when we use Typeof to judge two types, which is a relic of history. Returns true when we compare two types of values using a double equal sign, false when we compare two types of values with three equal signs.Copy the code

For more information, see “JavaScript in Depth: Undefined and NULL”

8. How to obtain the safe value of undefined?

Because undefined is an identifier, it can be used and assigned as a variable, but this will affect the normal judgment of undefined. The expression void ___ returns no value, so undefined is returned. Void does not change the result of the expression; it just makes the expression return no value. By convention we use void 0 to get undefined.Copy the code

9. What are some basic rules for writing JavaScript?

In normal project development, we follow some basic rules such as: (1) a function scope of all variable declarations should be mentioned function first, use a var statement, not allowed two consecutive var statement, the statement If the variable has no value, should give the initial value of the variable assignment of the corresponding type, facilitate others when reading code, can be clear at a glance know variables corresponding to the types of values. (2) The address, time and other strings in the code need to be replaced by constants. (3) Use '===', '! ==' instead of '==', '! = '. (4) Do not add methods on the prototype of built-in objects, such as Array and Date. (5) Switch statements must have a default branch. (6) The for loop must use braces. (7) If statements must use braces.Copy the code

10. JavaScript prototype, prototype chain? What are the characteristics?

In JS we use constructors to create objects. Each constructor has a prototype property value inside it. This property value is an object containing properties and methods that can be shared by all instances of the constructor. When we create an object using the constructor, the object contains a pointer to the constructor's prototype property. In ES5, this pointer is called the prototype of the object. Normally we should not be able to get this value, but browsers now implement the __proto__ attribute to give us access to this attribute, but it is best not to use this attribute because it is not specified in the specification. New to ES5 is the object.getProtoTypeof () method, which can be used to retrieve the Object's prototype. When we access a property of an object, if that property doesn't exist inside the object, then it will look for that property in its prototype object, and that prototype object will have its own prototype, and so on and so forth, the concept of prototype chain. The end of the prototype chain is usually Object.prototype, so that's why new objects can use methods like toString(). Features: JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change.Copy the code

For more information, see “JavaScript In-depth Understanding of Prototypes and Prototype Chains.”

11. How does JS get the prototype?

1) p. __proto__ (2) p.c onstructor. Prototype (3)Object.getPrototypeOf(p)
Copy the code

12. The representation of different base numbers in JS

(1) The value starts with 0X or 0X in hexadecimal format. (2) octal numbers starting with 0, 0O and 0O. (3) Representations starting with 0B and 0B are binary formats.Copy the code

13. What is the safe range of integers in JS?

A safe integer is an integer in this range that can be converted to binary storage without loss of precision. The maximum integer that can be safely rendered is 2^ 53-1, that is, 9007199254740991, defined as number. MAX_SAFE_INTEGER in ES6. The minimum integer is -9007199254740991, which is defined as number.min_safe_INTEGER in ES6. If a calculation results in a value that is outside the JavaScript value range, the value is automatically converted to a special Infinity value. If one calculation returns a positive or negative Infinity value, that value will not participate in the next calculation. To determine whether a number isFinite, use the isFinite function.Copy the code

14. What is the result of typeof NaN?

NaN means "not a number," and NaN is a sentinel value (a general value for a special purpose) used to indicate an error situation in a number type, that is, "the result of a failure to perform a mathematical operation." typeof NaN; // "number" NaN is a special value that is not equal to itself and is the only non-reflexive value. NaN! = NaN is true.Copy the code

What is the difference between isNaN and number. isNaN?

The function isNaN takes an argument and tries to convert it to a value. Any value that can't be converted to a value returns true, so non-numeric values also return true, affecting NaN's judgment. The function number. isNaN determines whether the argument passed is a Number first, and if it is a Number then whether it is a NaN, which is more accurate for NaN.Copy the code

16. What happens when the Array constructor has only one parameter value?

When the Array constructor takes only one numeric argument, that argument is used as the default length of the Array, rather than as an element in the Array. This creates an empty array with its length property set to the specified value. Constructor Array(..) The new keyword is not required. If not, it will be automatically replaced.Copy the code

17. Other rules for converting values to strings?

Section 9.8 of the specification defines the abstract operation ToString, which handles non-string-to-string casts. (1) Null and Undefined, Null to Null, Undefined to "Undefined", (2) Boolean, true to "true", false to "false". (3) The value of type Number is converted directly, but the very small and the very large numbers are used in exponential form. (4) The value of Symbol type is directly converted, but only explicit casts are allowed. Using implicit casts will cause errors. (3) for ordinary objects defined unless the toString () method, or you will call the toString () (Object. The prototype. The toString () to return the internal properties of [[Class]] value, such as "[Object Object]". If an object has its own toString() method, that method is called and its return value is used when stringified.Copy the code

18. Conversion rules for other values to numeric values?

Sometimes we need to treat non-numeric values as numbers, such as math operations. For this purpose, the ES5 specification defines the abstract operation ToNumber in Section 9.3. (1) The value of Undefined is converted to NaN. (2) A value of Null type is converted to 0. Boolean values, true to 1 and false to 0. (4) String values are converted as if using the Number() function. If it contains a non-numeric value, it is converted to NaN and the empty String is 0. (5) The value of Symbol type cannot be converted to numbers, and an error will be reported. (6) Objects (including arrays) are first converted to the corresponding primitive type value. If a non-numeric primitive type value is returned, it is forced to be converted to a number following the above rules. In order to convert a value to the corresponding primitive type value, the abstract operation ToPrimitive first checks (through the internal operation DefaultValue) whether the value has a valueOf() method. If a primitive type value is present and returned, that value is used for the cast. If not, the return value of toString() is used (if present) for the cast. If neither valueOf() nor toString() returns a base type value, TypeError is generated.Copy the code

19. How to convert other values to Boolean values?

The abstract operation ToBoolean, defined in Section 9.2 of the ES5 specification, lists all possible results of a Boolean cast. The following are false values: • undefined • null • false • +0, -0, and NaN • "" False Boolean casts result in false. Logically, anything outside the list of false values should be true.Copy the code

20. What are the results of valueOf and toString for {} and []?

ValueOf {} is {}, toString is "[object object]" [], toString is ""Copy the code

21. What is a false value object?

In certain cases, browsers create their own exotic values based on normal JavaScript syntax. These are "false value objects." False value objects look like normal objects (they all have attributes, etc.), but the most common example of casting them to a Boolean that yields false is document.all, which is an array-like object that contains all the elements on a page, The DOM (not the JavaScript engine) is provided for use by JavaScript programs.Copy the code

22. What does the ~ operator do?

~ returns the complement of 2, and ~ converts the number to a 32-bit integer, so we can use ~ for rounding. ~x is roughly the same thing as - x+1.Copy the code

23. What is the difference between parsing a number in a string and casting a string to a number, which both return a number?

Parsing allows non-numeric characters in strings (such as parseInt()) in left-to-right order, stopping if non-numeric characters are encountered. Conversions (such as Nu mber ()) do not allow non-numeric characters, or they fail and return NaN.Copy the code

24. +When is the operator used to concatenate strings?

According to section 11.6.1 of the ES5 specification, + will be concatenated if an operand is a string or can be converted to a string by the following steps. If one of its operands is an object (including an array), the ToPrimitive abstract operation is called on it first, which in turn calls [[DefaultValue]], with the number as the context. If it cannot be converted to a string, it is converted to a numeric type for evaluation. To put it simply, if one of the operands of + is a string (or if the above steps result in a string), string concatenation is performed, otherwise number addition is performed. So for operators other than addition, as long as one side is a number, the other side is converted to a number.Copy the code

25. When can implicit casts of Booleans occur?

(1) If (...) A conditional expression in a statement. (2) For STH. ; . ; ..) The conditional expression in the statement (second). (3) While (...) And do.. while(..) A conditional judgment expression in a loop. (4)? The conditional judgment expression in:. (5) logical operators | | (logical or) and && (and logic) than the left operand () as a conditional expression.Copy the code

26. | | and && operator returns a value?

&& and | | first judgment can be carried to the first operand condition, if it is not a Boolean value to ToBoolean casts, and then execute condition judgment. For | |, if the condition judgment result to true will return the value of the first operand, if to false will return the value of the second operand. &&, on the other hand, returns the value of the second operand if true or the value of the first operand if false. && and | | return values of them one of the operands, and unconditioned judgment resultCopy the code

27. Cast value of Symbol?

ES6 allows explicit casts from symbols to strings, however implicit casts produce errors. The Symbol value cannot be cast to a number (both explicit and implicit yield an error), but can be cast to a Boolean value (both explicit and implicit yield true).Copy the code

28. Cast rules for the == operator?

(1) The equality comparison between strings and numbers, and the comparison is made after converting strings to numbers. (2) Equality comparison between other types and Boolean types, first converts Boolean values to numbers, and then applies other rules for comparison. (3) Null and undefined equal comparison, result is true. Comparisons with other values return false values. (4) Equality comparison between objects and non-objects, objects call ToPrimitive abstract operation first, then compare. (5) Equality comparison returns false if an operation has a NaN value (NaN itself is not equal to NaN). (6) If both operation values are objects, then compare whether they refer to the same object. The equality operator returns true if both operands refer to the same object, false otherwise.Copy the code

See “JavaScript String Comparisons” for more information.

29. How do I convert a string to a number, such as ‘12.3b’?

(1) Use the Number() method, provided that the contained string does not contain illegal characters. ParseInt () parseInt() parseInt() parseInt() parses a string and returns an integer. You can also set the cardinality of the number to parse. When the cardinality value is 0 or not set, parseInt() determines the cardinality of a number based on string. (3) Use the parseFloat() method, which parses a string argument and returns a floating point number. (4) Implicit conversion using the + operator.Copy the code

Number(), parseInt(), parseFloat(), parseFloat()

30. How do I add commas every three digits to the left of the floating point point, such as 12000000.11, to “12,000,000.11”?

 function format(number){
      return number && number.replace(/ (? ! (^)? =(\d{3})+\.) /g.",")}Copy the code

31. Common regular expressions

1) matches16Base color valuevar regex = /#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g; (2) matches the date in yyyY-MM-DD formatvar regex = / ^ [0-9] {4} - (0 [1-9] | [0-2] 1) - (0 | [1-9] [12] [0-9] [01]) | 3 $/; (3Match the QQ numbervar regex = / ^ (1-9] [0-9] {4, 10} $/ g; (4) The mobile number is regularvar regex = /^1[34578]\d{9}$/g; (5The user name is regularvar regex = / ^ [a zA - Z \ $] [a zA - Z0 - _ \ $9] $/ dec {4};
Copy the code

For more information, please refer to “15 JS Regular Expressions commonly used for Front-end form Validation” and “SUMMARY of JS Regular Expressions commonly used”.

32. Various methods for generating random numbers?

Methods for generating random numbers (Different Ranges and Types of random numbers)

33. How to implement random array sort?

1Use the array sort method to randomly sort the elements of the arrayMath. Random () and0.5Compare, return if greater than1Swap bits, return - if less than1, do not swap places.function randomSort(a, b) { 
       return Math.random() > 0.5 ? -1 : 1; } disadvantages: The location of each element to the new array is not random, because the sort() method is compared sequentially. (2Extract a random element from the original array and add it to the new arrayfunction randomSort(arr) {
         var result = [];

         while (arr.length > 0) {
             var randomIndex = Math.floor(Math.random() * arr.length);
             result.push(arr[randomIndex]);
             arr.splice(randomIndex, 1);
         }

         returnresult; } (3Swap elements in an array randomly (shuffle algorithm is similar)function randomSort(arr) {
       var index,
         randomIndex,
         temp,
         len = arr.length;

       for (index = 0; index < len; index++) {
         randomIndex = Math.floor(Math.random() * (len - index)) + index;

         temp = arr[index];
         arr[index] = arr[randomIndex];
         arr[randomIndex] = temp;
       }

       return arr;
     }
     
     // es6
     function randomSort(array) {
       let length = array.length;

       if (!Array.isArray(array) || length <= 1) return;

       for (let index = 0; index < length - 1; index++) {
         let randomIndex = Math.floor(Math.random() * (length - index)) + index;

         [array[index], array[randomIndex]] = [array[randomIndex], array[index]];
       }

       return array;
     }

Copy the code

For more information, see: Fisher and Yates original, javascript For Random Array Sorting? JavaScript Learning Notes: Sorting arrays randomly

34. How many ways can javascript create objects?

We usually create objects in literal form, but this creates a lot of duplicate code when creating lots of similar objects. But js is different from general object-oriented languages in that it had no concept of classes prior to ES6. However, we can use functions to simulate and generate reusable object creation methods. I have learned that there are several methods: (1) The first one is factory mode. The main working principle of factory mode is to use functions to encapsulate the details of object creation, so as to achieve the purpose of reuse by calling functions. But it has a big problem is that the object created can not be associated with a type, it simply encapsulates the reusable code, but does not establish the relationship between the object and the type. (2) The second is the constructor pattern. Every function in JS can be used as a constructor, as long as a function is called by new, then we can call it a constructor. Executing the constructor first creates an object, then points the prototype of the object to the constructor's Prototype property, then points this in the execution context to the object, and finally executes the entire function, returning the newly created object if the return value is not an object. Since the value of this refers to the newly created object, we can use this to assign a value to the object. The advantage of the constructor pattern over the factory pattern is that the object created is associated with the constructor, so that we can identify the type of the object from the stereotype. Constructor exists a disadvantage is that caused unnecessary function to like the creation of a because in js function is an object, so if the object attribute contains the function, so every time we will create a new function of elephant, wasted unnecessary memory space, because the function is all instances can be generic. (3) The third pattern is the prototype pattern, because every function has a prototype attribute, which is an object containing properties and methods that are shared by all instances created through the constructor. Therefore, we can use prototype objects to add common properties and methods for code reuse. Compared with the constructor pattern, this method solves the reuse problem of function objects. One is that there is no way to initialize a value by passing in a parameter. The other is that if there is a value of a reference type such as Array, then all instances share the same object, and a change in the value of a reference class by one instance affects all instances. (4) The fourth pattern is the combination of the constructor pattern and the stereotype pattern, which is the most common way to create custom types. Because both the constructor pattern and the prototype pattern are problematic to use separately, we can combine the two patterns, using constructors to initialize object properties and using prototype objects to reuse function methods. This approach is a good solution to the disadvantages of using the two patterns separately, but it is not good enough to encapsulate the code because the two different patterns are used. (5) The fifth mode is the dynamic prototype mode, which moves the creation process of the prototype method assignment inside the constructor. By judging whether the attribute exists, it can achieve the effect of assigning the prototype object only once at the first call of the function. This approach nicely encapsulates the above blending patterns. (6) The sixth pattern is the parasitic constructor pattern. The implementation of this pattern is basically the same as the factory pattern. My understanding of this pattern is that it is mainly based on an existing type and extends the instantiated object at instantiation time. This extends the object without modifying the original constructor. It has the same disadvantage as the factory pattern in that it cannot recognize objects. Well, that's what I've learned so far.Copy the code

For more information, see “Object Creation with JavaScript in Depth.”

35. How many ways can JavaScript inheritance be implemented?

There are several ways to implement inheritance in JS that I understand: (1) The first way is to implement inheritance in the way of prototype chain, but the drawback of this way is that when containing reference type data, it will be shared by all instance objects, which is easy to cause confusion of modification. Also, you cannot pass parameters to supertypes when creating subtypes. (2) The second method is to borrow the constructor. This method is realized by calling the constructor of the supertype in the function of the subtype. This method solves the disadvantage of not passing parameters to the supertype, but it has one problem is that it cannot realize the reuse of function methods. And the method subtypes defined by the supertype stereotype are not accessible. (3) The third method is combinatorial inheritance, which is a way to use a combination of stereotype chains and borrowed constructors. We implement inheritance of properties of types by borrowing constructors, and implement inheritance of methods by setting stereotypes of subtypes to instances of supertypes. This solves the problem of using the above two patterns in isolation, but since we used instances of the supertype as prototypes for subtypes, we called the superclass constructor twice, resulting in many unnecessary attributes in the subclass prototype. (4) The fourth way is the original type inheritance, the main idea of the original type inheritance is to create a new object based on the existing object, the principle of implementation is to pass an object to the function, and then return an object with this object as the prototype. The idea of inheritance is not to create a new type, but to implement a simple inheritance of an Object. The object.create () method defined in ES5 is an implementation of the original type inheritance. The disadvantage is the same as the prototype chain approach. (5) The fifth method is parasitic inheritance. The idea of parasitic inheritance is to create a function to encapsulate the inheritance process by passing in an object, then making a copy of the object, then extending the object, and finally returning the object. This process of extension can be understood as inheritance. The advantage of this inheritance is to implement inheritance on a simple object if the object is not of our custom type. The disadvantage is that there is no way to reuse the function. (6) The sixth method is parasitic combinatorial inheritance. The disadvantage of combinatorial inheritance is to use the instance of supertype as the prototype of subtype, which leads to the addition of unnecessary prototype belonging. Parasitic composite inheritance uses a copy of the stereotype of the supertype as the stereotype of the subtype, thus avoiding the creation of unnecessary attributes.Copy the code

For more information, see “Inheritance of JavaScript in Depth.”

Implementation of parasitic combinatorial inheritance?

 function Person(name) {
   this.name = name;
 }

 Person.prototype.sayName = function () {
   console.log("My name is " + this.name + ".");
 }

 function Student(name, grade) {
   Person.call(this, name);
   this.grade = grade;
 }

 Student.prototype = Object.create(Person.prototype);
 Student.prototype.constructor = Student;

 Student.prototype.sayMyGrade = function () {
   console.log("My grade is " + this.grade + ".");
 } 
Copy the code

37. Javascript’s scope chain?

The purpose of scope chains is to ensure orderly access to all variables and functions that the executing environment has access to. Through scope chains, we can access variables and functions of the outer environment. A scope chain is essentially a list of Pointers to a variable object. A variable object is an object that contains all variables and functions in the execution environment. The scope chain is always preceded by the variable object of the current execution context. The variable object of the global execution context (that is, the global object) is always the last object in the scope chain. When we look for a variable, we can look back down the scope chain if it is not found in the current execution environment. The creation of a scope chain is related to the establishment of the execution context....Copy the code

See “JavaScript in Depth: Scope Chains” for more information.

38. Talk about the understanding of This object.

This is an attribute in the execution context that points to the object on which the method was last called. In real development, the direction of this can be determined by four call modes. (1) The first is function call mode, when a function is called directly as a function that is not a property of an object, this refers to the global object. (2) The second is the method invocation pattern. If a function is called as a method of an object, this refers to that object. (3) The third is the constructor invocation mode. If a function is called with new, a new object is created before the function is executed. This refers to the newly created object. (4) The fourth is the apply, call, and bind call modes, which can display the this reference of the specified calling function. The apply method takes two parameters: an object bound to this and an array of parameters. The call method receives arguments, the first of which is the object of the this binding, followed by the remaining arguments passed into the function to execute. That is, when using the call() method, the arguments passed to the function must be enumerated one by one. The bind method passes in an object and returns a new function with this bound to the object. The this pointer to this function does not change except when new is used. Of the four, the constructor invocation pattern has the highest priority, followed by apply, Call, and bind, followed by method invocation, and then function invocation.Copy the code

An in-depth understanding of JavaScript

39. What does Eval do?

Its function is to parse the corresponding string into JS code and run it. Eval should be avoided as it is unsafe and very performance-intensive (2 times, once parsed into JS and once executed).Copy the code

See Eval () for more information.

40. What is DOM and BOM?

DOM refers to the Document Object Model, which treats a document as an object that defines the methods and interfaces used to process web content. BOM refers to the Browser object model, which treats the browser as an object that defines the methods and interfaces for interacting with the browser. At the heart of the BOM is the Window, and the Window object has a dual role as both an interface to access the browser window through JS and a Global object. This means that any object, variable, or function defined in the web page exists as a property or method of the global object. The Window object contains sub-objects such as the Locati on object, the Navigator object, and the Screen object, and the document object, the most fundamental object of the DOM, is also a sub-object of the WINDOW object of the BOM.Copy the code

For more information, please refer to “What’s the difference between DOM, DOCUMENT, BOM and WINDOW? “Window Object” “What are DOM and BOM and how are they related?” “JavaScript Learning Summary (3) BOM and DOM details”

41. Write a generic event listener function.

 const EventUtils = {

   / / sight, respectively dom0 | | dom2 | | IE way to bind the event
   // Add events
   addEvent: function (element, type, handler) {
     if (element.addEventListener) {
       element.addEventListener(type, handler, false);
     } else if (element.attachEvent) {
       element.attachEvent("on" + type, handler);
     } else {
       element["on"+ type] = handler; }},// Remove the event
   removeEvent: function (element, type, handler) {
     if (element.removeEventListener) {
       element.removeEventListener(type, handler, false);
     } else if (element.detachEvent) {
       element.detachEvent("on" + type, handler);
     } else {
       element["on" + type] = null; }},// Get the event target
   getTarget: function (event) {
     return event.target || event.srcElement;
   },

   // Get a reference to the event object, get all the information about the event, and ensure that the event is always available
   getEvent: function (event) {
     return event || window.event;
   },

   // Prevent events (mainly event bubbling, since IE does not support event capture)
   stopPropagation: function (event) {
     if (event.stopPropagation) {
       event.stopPropagation();
     } else {
       event.cancelBubble = true; }},// Cancel the default behavior of the event
   preventDefault: function (event) {
     if (event.preventDefault) {
       event.preventDefault();
     } else {
       event.returnValue = false; }}}Copy the code

For details, please refer to JS Event Model.

42. What was the event? What’s the difference between IE and Firefox’s event mechanism? How do I stop bubbling?

(1) Events are interactive actions that occur when users operate web pages, such as Click/Move. In addition to actions triggered by users, events can also include document loading, window scrolling and size adjustment. An event is encapsulated as an event object that contains all the information about when the event occurs (the properties of the event) and the actions that can be performed on the event (the methods of the event). (2) Event processing mechanism: IE supports event bubbling, Firefox supports two event models at the same time, that is, event bubbling and event capture. (3) Event.stopPropagation () or ie event.cancelBubble = true;Copy the code

For more information, see “Javascript Event Model series 1: Events and the Three Models of Events”, “Javascript Event Model: Event Capture and Event Bubbling”.

43. What are the three event models?

Events are the interactive actions or operations of the web page. There are three event models in modern browsers. The first event model is the original DOM0 level model. This model does not propagate, so there is no concept of event flow, but some browsers now support bubbling implementation, which can define listeners directly in the web page, or can specify listeners through JS properties. This approach is compatible with all browsers. The second event model is the IE event model, in which an event has two processes, the event processing phase and the event bubbling phase. The event processing phase first executes the listening event for the target element binding. Then there is the event bubbling phase, bubbling refers to the event bubbling from the target element to the document, checking whether the passing node is bound to the event listener function, and executing it if so. This model uses attachEvent to add listeners. Multiple listeners can be added and executed sequentially. The third is the DOM2 level event model, in which an event has three processes, the first process is the event capture stage. Capture refers to the propagation of events from the docu ment all the way down to the target element, checking in turn to see if passing nodes are bound to event listeners, and executing if so. The latter two phases are the same as the two phases of the IE event model. In this event model, the event-bound function is addEventListener, where the third parameter specifies whether the event is executed during the capture phase.Copy the code

For more information, see bubbling or Capturing when multiple events are bound to a DOM element.

44. What is event delegation?

Event delegation essentially leverages the browser event bubbling mechanism. Since the event is uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, the listener function of the child node can be defined on the parent node, and the listener function of the parent node can uniformly handle the events of multiple child elements, which is called event proxy. Using the event broker we can reduce memory consumption by eliminating the need to bind a listening event to each child element. We can also implement the dynamic binding of events by using the event broker. For example, when a new child node is added, we do not need to add a separate listening event to it, and its events will be handled by the listener function in the parent element.Copy the code

For more information, see JavaScript Event Delegation in Detail.

[“1”, “2”, “3”].map(parseInt)

The parseInt() function parses a string and returns an integer, taking two arguments (val, radix), where radix represents the basis of the number to be parsed. (The value is between 2 and 36, and the numbers in the string cannot be greater than the radix to correctly return numeric result values). The map passes three parameters (element, index, array). By default, the third parameter is ignored, so the three parameters are "1-0", "2-1", and "3-2". Because the string value cannot be greater than the base, the next two calls fail. The first time the base is 0, and decimal parsing returns 1.Copy the code

For details, see: why [“1”, “2”, “3”].map(parseInt) Returns [1,NaN,NaN]?

46. What is a closure and why do you use it?

A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function within a function that has access to local variables of the current function. Closures have two common uses. The first use of closures is to enable us to access variables inside functions outside of them. By using closures, we can access variables inside the function by calling the closure function externally. We can use this method to create private variables. Another use of a function is to keep a variable object in the context of a function that has already run out of memory. Because the closure retains a reference to the variable object, the variable object is not reclaimed. In fact, the essence of closure is a special application of scope chain. As long as you understand the creation process of scope chain, you can understand the implementation principle of closure.Copy the code

For more information, see JavaScript In Depth closures.

47. “use strict” in javascript code; What does that mean? What’s the difference in using it?

Related knowledge:

Use Strict is a (strict) runtime mode added by ECMAscript5 that makes Javascript run under stricter conditions. The purpose of setting up "strict mode" is mainly as follows: - To eliminate some unreasonable and unrigorous aspects of Javascript syntax and reduce some weird behaviors; -Eliminate some unsafe parts of the code operation to ensure the safety of the code operation; - Improve compiler efficiency, increase running speed; - Setting the stage for future versions of Javascript. (1) Do not use the with statement. (2) Disallow this keyword from pointing to global objects. (3) Objects cannot have identical attributes. .Copy the code

Answer:

Use strict refers to strict running mode, in which the use of JS is restricted. Such as disallowing this to refer to global objects, and disallowing the with statement. The purpose of setting up strict mode is to eliminate some unsafe ways of using code, and also to eliminate some unreasonable parts of JS syntax itself, so as to reduce some weird behavior at runtime. Using strict run mode also improves compilation efficiency, which in turn makes your code run faster. I think strict mode represents a more reasonable, safer, more rigorous js development direction.Copy the code

For more information, see “Javascript Strict Mode In Detail”.

48. How do I determine whether an object belongs to a class?

The first is to use the instanceof operator to determine whether the constructor's Prototype property appears anywhere in the object's prototype chain. The second approach can be determined by the object's constructor property, which points to the object's constructor, but this approach is not very safe because the constructor property can be overridden. The third way, if you need to determine is a built-in reference type, you can use the Object. The prototype, the toString () method to print the Object's [[Class]] attribute to determine.Copy the code

For more information, please refer to js to determine whether an object belongs to a certain class.

49. The role of Instanceof?

 instanceofThe prototype operator is used to determine whether the constructor's prototype property appears anywhere in the object's prototype chain. Implementation:function myInstanceof(left, right) {
   let proto = Object.getPrototypeOf(left), // Get the prototype of the object
     prototype = right.prototype; // Get the constructor's prototype object

   // Check whether the constructor's prototype object is on the prototype chain
   while (true) {
     if(! proto)return false;
     if (proto === prototype) return true;

     proto = Object.getPrototypeOf(proto); }}Copy the code

For more information: Instanceof

50. What exactly does the new operator do? How to do that?

1First, a new empty object is created (2) sets the prototype of the object to the function's prototype object. (3) of the functionthisPoint to the object and execute the constructor code (add attributes to the new object) (4) determines the return value type of the function and, if it is a value type, returns the created object. If it is a reference type, an object of that reference type is returned. Implementation:function objectFactory() {

   let newObject = null.constructor = Array.prototype.shift.call(arguments),
     result = null;
   
   // Determine the parameters
   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

See “What does the New operator do?” for details. Mock Implementation of JavaScript Deep New

51. In Javascript, there is a function that executes an object lookup but never looks up the prototype. What is this function?

HasOwnProperty All objects that inherit from Object inherit to the hasOwnProperty method. This method can be used to detect whether an object has specific attributes of itself. Unlike the IN operator, this method ignores attributes inherited from the stereotype chain.Copy the code

Details you can refer to: the Object. The prototype. HasOwnProperty ()”

52. What do you know about JSON?

Related knowledge:

JSON is a data interchange format, text-based, superior to lightweight, for exchanging data. JSON can represent numbers, booleans, strings, NULL, arrays (ordered sequences of values), and objects made up of these values (or arrays, objects) (mappings between strings and values). JSON uses JavaScript syntax, but the JSON format is just text. Text can be read by any programming language and passed as a data format.Copy the code

Answer:

JSON is a lightweight text-based data interchange format. It can be read by any programming language and passed as a data format. In the development of the project, we used JSON as a way of exchanging data between the front and back ends. In the front end, we serialize a data structure in JSON format into A JSON string, and then transfer it to the back end. The back end generates the corresponding data structure after parsing the STRING in JSON format, so as to achieve a transfer of data from the front and back ends. Because JSON syntax is based on JS, it is easy to confuse JSON with objects in JS. However, it should be noted that objects in JSON are not the same as objects in JS. Objects in JSON are more strictly formatted. You can't have property values like NaN, so most JS objects don't fit the JSON object format. Two functions are provided in JS to convert THE JS data structure to JSON format. One is the json. stringify function, which converts a jSON-formatted data structure to a JSON string by passing it in. If the incoming data structure does not conform to the JSON format, the values are treated specially during serialization to make them conform to the specification. We can call this function to convert the data object to a JSON-formatted string when the front end sends data to the back end. Another function, the json.parse () function, converts jSON-formatted strings to a JS data structure and throws an error if the string passed is not a standard JSON-formatted string. When we receive a JSON-formatted string from the back end, we can use this method to parse it into a JS data structure for data access.Copy the code

For more information, see: JSON in JavaScript in Depth.

53. [].forEach.call($$(““),function(a){a.style.outline=”1px solid #”+(~~(Math.random()(1<<24)).toString(16)}) Can you explain what this code means?

(1) Select all DOM elements of the page. In the browser's console can use $$() method to get the page, the corresponding element in this is modern browsers provide a life Make line API is equivalent to the document. QuerySelectorAll method. (2) Loop over the DOM element (3) add outline to the element. Since the rendered outline is not in the CSS box model, adding an outline to an element does not affect the size of the element or the layout of the page. (4) Generate random color function. Math.random()*(1<<24) yields a random number between 0 and 2^ 24-1, because it is a floating-point number, but we only need the integer part, and then use the toString(16) operator. Convert to a hexadecimal string.Copy the code

For more information, see: Learning JavaScript with a Line of Code

54. What are the ways of js lazy loading?

Related knowledge:

Js lazy loading, which means loading JavaScript files after the page has finished loading. Js lazy loading helps speed up page loading. The following methods are generally available: defer attribute Async attribute dynamic DOM creation mode Use the setTimeout delay method to let the JS finally loadCopy the code

Answer:

The loading, parsing, and execution of JS will block the rendering process of the page, so we want js scripts to load as lazily as possible to improve the rendering speed of the page. The first way I learned is that we usually put the JS script at the bottom of the document so that the JS script can be loaded and executed as late as possible. The second option is to add the defer attribute to the JS script, which will allow the script load to be parsed at the same time as the document is parsed, and then execute the script file when the document is parsed, so that the rendering of the page is not blocked. Several scripts with the defer property set end up executing sequentially by specification, but this may not be the case in some browsers. The third way is to add async property to the JS script. This property causes the script to load asynchronously and does not block the page parsing process. However, executing the JS script immediately after the script is loaded will also block if the document is not parsed. Scripts with multiple async properties are unpredictable in order of execution and will not be executed in code order. The fourth way is to dynamically create DOM tags. We can monitor the loading event of the document, and then dynamically create script tags to introduce JS scripts after the document is loaded.Copy the code

For more information, see “Several ways to lazy load JS” and “HTML 5”

55. What is Ajax? How do I create an Ajax?

Related knowledge:

 2005years2The term AJAX was first coined in Asynchronous JavaScript and XML, referring to Asynchronous JavaScript communication in which data is extracted from an XML document retrieved from a server and then updated to the corresponding portion of the current web page. Instead of refreshing the entire page. Specifically, AJAX involves the following steps. (1Create an XMLHttpRequest object, that is, create an asynchronous call object (2) creates a new HTTP request and specifies the HTTP request method, URL, and authentication information (3) sets the function that responds to changes in HTTP request status (4) sending HTTP requests (5) get the data returned by the asynchronous call (6Local refresh with JavaScript and DOMconst SERVER_URL = "/server"

 let xhr = new XMLHttpRequest();

 // Create an Http request
 xhr.open("GET", SERVER_URL, true);

 // Set the status listener function
 xhr.onreadystatechange = function () {
   if (this.readyState ! = =4) return;

   // When the request succeeds
   if (this.status === 200) {
     handle(this.response);
   } else {
     console.error(this.statusText); }}// Set the listener function when the request fails
 xhr.onerror = function () {
   console.error(this.statusText);
 }

 // Set the request header information
 xhr.responseType = "json";
 xhr.setRequestHeader("Accept"."application/json");

 // Send an Http request
 xhr.send(null); Promise encapsulates the implementation:function getJSON(url) {

   // Create a Promise object
   let promise = new Promise(function (resolve, reject) {

     let xhr = new XMLHttpRequest();

     // Create an HTTP request
     xhr.open("GET", url, true);

     // Set the status listener
     xhr.onreadystatechange = function () {

       if (this.readyState ! = =4) return;

       // Change the state of the promise when the request succeeds or fails
       if (this.status === 200) {
         resolve(this.response);
       } else {
         reject(new Error(this.statusText)); }}// Set the error listener
     xhr.onerror = function () {
       reject(new Error(this.statusText));
     }
     
     // Set the data type of the response
     xhr.responseType = "json";

     // Set the request header information
     xhr.setRequestHeader("Accept"."application/json");

     // Send an HTTP request
     xhr.send(null);

   })

   return promise;
 }
Copy the code

Answer:

My understanding of Ajax is that it is a way to communicate asynchronously, by sending HTTP communication directly from a JAVASCRIPT script to the server, and then updating the corresponding part of the web page based on the data returned by the server without refreshing the entire page. There are several steps to creating an Ajax, starting with creating an XMLHttpRequest object. An HTTP request is then created on this object using the open method, which takes parameters such as the request method, the address of the request, asynchrony, and the authentication information of the user. Before making the request, we can add some information and listener functions to the object. For example, we can use the setRequestHeader method to add header information to the request. We can also add a state listener to this object. An XMLHttpRequest object has five states. When its states change, the on readyStatechange event is triggered. You can set up a listener function to handle the result of a successful request. When the readyState of the object changes to 4, the data returned by the proxy server is received. At this time, we can judge the status of the request. If the status is 2XX or 304, it means that the return is normal. At this point we can update the page with the data in response. When the properties and listener functions of the object are set up, we finally call the SENT method to make a request to the server, passing in parameters as the body of data to be sent.Copy the code

For more information, see: XMLHttpRequest Objects, Ajax to Fetch, Axios, Fetch Primer, Traditional Ajax is Dead, Fetch Lives

56. What about browser caching?

The browser caching mechanism means that by keeping a copy of a received Web resource for a certain period of time, if a second request for that resource is made within the lifetime of the resource, the browser will use the cached copy directly instead of making a request to the server. Using Web cache can effectively improve the speed of page opening and reduce unnecessary network bandwidth consumption. The cache policy of Web resources is generally specified by the server, which can be divided into two types: strong cache policy and negotiated cache policy. If the cache resource is valid, the cache resource is directly used without sending requests to the server. Strong caching policies can be set in two ways: the Expires attribute and the cache-control attribute in HTTP headers. The server specifies the expiration time of the resource by adding an Expires attribute to the response header. After expiration, the resource can be used by the cache without sending requests to the server. This time is an absolute time, it is the server time, so there may be a problem that the client time is inconsistent with the server time, or the user can modify the client time, which may affect the cache hit results. Expires is the way it was in HTTP1.0, and because of some of its shortcomings, a new header attribute was proposed in HTTP 1.1: the cache-control attribute, which provides more precise Control over the caching of resources. It has a lot of different values. Common ones are, for example, we can specify the amount of time a resource can be cached by setting max-age. This is a relative time, and it will calculate the expiration time of the resource based on the size of the time and the time when the resource was first requested. This is more efficient. Another common example is private, which specifies that resources can only be cached by clients, not proxy servers. For example, n o-store is used to specify that a resource cannot be cached. No-cache indicates that the resource can be cached but is invalid immediately. A request must be sent to the server each time. In general, you only need to set one or the other to implement a strong caching policy, and cache-control takes precedence over Expires when both are used together. With a negotiated cache policy, a request is first sent to the server, and if the resource has not been modified, a 304 status is returned, allowing the browser to use the local cache copy. If the resource has been modified, the modified resource is returned. The negotiated cache can also be set in two ways: the Etag and last-mod attributes in the HTTP header. The server indicates when the resource was Last Modified by adding a last-Modified attribute to the response header. The next time the browser makes a request, it adds an if-Modified-since attribute to the request header. Property is the last-Modified value of the Last resource returned. When a request is sent to the server, the server compares this property with the last modification time of the resource to determine whether the resource has been modified. If the resource has not been modified, return to status 304 and let the client use the local cache. If the resource has been modified, the modified resource is returned. A disadvantage of using this method is that the Last modification time of last-Modified is only accurate to the level of seconds. If some files are Modified more than once in less than one second, the file will have changed but last-Modified is not changed, which will cause inaccurate cache hits. Because of the possibility of last-Modified inaccuracies, HTTP provides an alternative, the Etag attribute. When the server returns a resource, it adds an Etag attribute to the header. This attribute is the unique identifier generated by the resource, and this value can change when the resource changes. The next time the resource is requested, the browser adds an if-none-match attribute to the request header. The value of this attribute is the Etag value of the last resource returned. After receiving the request, the service compares this value with the current Etag value of the resource to determine whether the resource has changed and whether it needs to return the resource. In this way, it is more accurate than the last-Modified method. When last-Modified and Etag attributes are present together, Etag takes precedence. When using a negotiated cache, the server needs to consider load balancing, so last-Modified resources on multiple servers should be the same. Since Etag values are different on each server, it is best not to set the Etag attribute when considering load balancing. Both the strong cache and negotiated cache policies use the local cache copy directly in case of a cache hit, except that the negotiated cache sends a request to the server once. Both send requests to the server to retrieve resources when the cache is down. In the actual caching mechanism, the strong caching policy and the negotiated caching policy are used together. The browser first determines whether the strong cache hit the request based on the requested information, and if so, directly uses the resource. If the negotiation cache is matched, the server does not return the resource and the browser uses the copy of the local resource. If the negotiation cache is not matched, the browser returns the latest resource to the browser.Copy the code

For details, please refer to: “Brief Introduction to Browser Cache” “Front-end optimization: Introduction to Browser Cache technology” “Cache-Control in request Headers” “Cache-Control Field value details”.

57. Ajax for Browser caching?

(1) before the ajax request. Plus anyAjaxObj setRequestHeader (" the if-modified-since ", "0"). (2) plus anyAjaxObj before ajax requests. SetRequestHeader (" cache-control ", "no - Cache"). (3) Add a random number to the URL: "fresh=" + math.random (); . "Nowtime =" + new Date().getTime(); . $.ajaxsetup ({cache:false}) $.ajaxsetup ({cache:false}) So all the Ajax on the page will execute this statement without having to save the cache record.Copy the code

For more information, please refer to: Solutions to Browser Caching Problems in Ajax

58. What is the difference between synchronous and asynchronous?

Related knowledge:

Synchronization, which can be understood as the execution of a function or method, waiting for the system to return a value or message, then the program is blocked, only after receiving the returned value or message to execute other commands. Asynchronous: After the function or method is executed, there is no need to wait for the return value or message obstructively, but only need to entrust an asynchronous process to the system. Then when the system receives the return value or message, the system will automatically trigger the entrusted asynchronous process to complete a complete process.Copy the code

Answer:

Synchronization means that when a process executes a request, if it takes a while for the request to return, the process will wait until the message returns and then proceed. Asynchronism means that when a process executes a request and waits for a period of time to return the request, the process will continue to execute the request without blocking the waiting message. When the message returns, the system will notify the process to process it.Copy the code

For more information, see the Difference between Synchronous and asynchronous.

59. What is the same origin policy for browsers?

My understanding of the browser's same-origin policy is that JS scripts in one domain cannot access content in another domain without permission. In this case, the protocols, domain names, and port numbers of the two domains must be the same. Otherwise, the two domains do not belong to the same domain. The same Origin policy mainly restricts three aspects. First, JS scripts in the current domain cannot access cookies, localStorage, and indexDB in other domains. The second is that js scripts in the current domain cannot manipulate the DOM in other domains. The third is that Ajax cannot send cross-domain requests under the current domain. Main aim of the same-origin policy is to ensure that the user information security, it's just a limit of js script, is not the limitation on the browser, for general img or script script requests will not cross-domain limitation, that is because these operations are not through the response result to possible security problems.Copy the code

60. How to solve cross-domain problems?

Related knowledge:

Hash + iframe (4) window.name + iframe (5) postMessage Cross-domain (6) Cross-domain resource sharing (CORS) (7) Cross-domain nginx proxy (8) Cross-domain NodeJS middleware proxy (9) cross-domain WebSocket protocolCopy the code

Answer:

The approach to cross-domain solutions can be divided according to what we want to achieve. First of all, if we only want to implement cross-domain operation of different subdomains under the master domain name, we can use document.domain to solve the problem. (1) Document.domain is set as the master domain name to achieve cross-domain operation of the same sub-domain name. At this time, cookies under the master domain name can be accessed by the quilt domain name. If the document contains an iframe with the same primary domain name and different subdomains, we can also operate on this iframe. If you want to solve the problem of communication between different cross-domain Windows, such as a page that wants to communicate with iframes from different sources within the page, you can use location.hash or window.name or postMessage. (2) Using the location.hash method, we can dynamically modify the hash value of the IFrame window on the main page, and then implement the listener function in the IFrame window to achieve such a one-way communication. Since there is no way to access the parent Windows of different sources in iframe, we cannot directly modify the hash value of the parent window to achieve communication. We can add another IFrame to the iframe, and the content of this iframe is the same as that of the parent page. So we can change the SRC of the top-level page with window.parent. Parent to achieve two-way communication. (3) The method of window.name is mainly based on the fact that after window.name is set in the same window, pages of different sources can also be accessed. Therefore, sub-pages of different sources can first write data in window.name and then jump to a page of the same origin as the parent. At this point, the level page can access the data in the wi ndow. Name of the same child page. The advantage of this method is that a large amount of data can be transmitted. (4) Use postMessage to solve the problem, which is a new API in H5. Through it, we can realize the information transfer between multiple Windows. By obtaining the reference of the specified window, we call postMessage to send the information. In the window, we receive the information by listening to the message information, so as to realize the information exchange between different sources. If it is a problem like ajax not being able to submit cross-domain requests, we can use JSONP, CORS, WebSocket protocol, server proxy to solve the problem. (5) The use of JSONP to achieve cross-domain request, its main principle is through the dynamic construction of script tag to achieve cross-domain request, because the introduction of script tag browser has no cross-domain access restrictions. This is done by specifying a callback function after the requested URL, and then when the server returns the data, it builds a wrapper around the JSON data, which is the callback function, and then returns it to the front end, and when the front end receives the data, it executes it directly because it's a script file. This allows the previously defined callback function to be called, enabling cross-domain request processing. This can only be used for GET requests. (6) The way to use CORS, CORS is a W3C standard, full name is "cross-domain resource sharing". CORS requires both browser and server support. Currently, all browsers support this functionality, so we only need to configure it on the server side. Browsers classify CORS requests into two categories: simple and non-simple. For simple requests, the browser issues CORS requests directly. In particular, an Origin field will be added to the header information. The Origin field specifies the source from which the request came. Based on this value, the server decides whether to approve the request or not. The server returns a normal HTTP response if Origin specifies a source that is not within the license scope. When the browser sees that the response header does not contain the Access-Control-Allow-Origin field, it knows that something has gone wrong, throws an error, and Ajax does not receive the response. If successful, it will contain fields starting with access-Control -. For non-simple requests, the browser sends a pre-check request to check whether the domain name is in the whitelist of the server. The browser sends a pre-check request only after receiving a positive reply. (7) Use webSocket protocol, which has no origin restriction. (8) Use the server to proxy the cross-domain access request, that is, when there is a cross-domain request operation, send the request to the back end, let the back end make the request for you, and then finally send back the obtained results.Copy the code

For more information, please refer to common Cross-domain Solutions on the front End (all), Browser Same-origin Policy and Its Circumvention, Cross-domain, All you Need to know here, Why Form Submission Does not have cross-domain Problems, but Ajax Submission Does?

61. How should cookies be handled when the server proxy forwards?

For more information, please refer to Nginx.

62. A quick word about cookies?

My understanding is that cookie is a data provided by the server for maintaining session status information, which is sent to the browser through the server. The browser saves it locally. When there is a request of the same origin next time, the saved cookie value is added to the request header and sent to the server. This can be used for things like logging a user's login status. Cookies typically store 4K of data and can only be accessed by shared web pages. Cookie information can be configured on the server side using the response header of set-cookie. A cookie contains five attributes: Expires, Domain, PATH, Secure, and HttpOnly. Domain is the domain name and path is the path. Together, domain and Path limit which urls the cookie can be accessed. Secure specifies that cookies can only be transmitted if security is ensured. HttpOnly specifies that cookies can only be accessed by the server, not js scripts. When a cross-domain request to XHR occurs, even same-origin cookies are not automatically added to the request header unless explicitly specified.Copy the code

For more information, see HTTP Cookies and Talk about Cookies.

63. How to do modular development?

My understanding of a module is that a module is a set of methods that implement a particular function. In the beginning, JS only realized some simple functions, so there was no concept of module, but as the program became more and more complex, the modular development of code became more and more important. Since functions have independent scope, the most primitive writing method is to use functions as modules, and several functions as a module, but this way is easy to cause global variables contamination, and there is no connection between modules. Object writing is proposed later, which addresses some of the drawbacks of using functions directly as modules by implementing functions as an object method, but this approach exposes all module members, and external code can modify the values of internal attributes. The most common approach is to write functions immediately, using closures to establish a module's private scope without contaminating the global scope.Copy the code

Detailed information can refer to: “Talk about modular development” “Javascript modular programming (a) : Module writing” “front-end modular: CommonJS, AMD, CMD, ES6” “Module syntax”

64. How many module specifications of JS?

There are four mature module loading schemes in JS. The first is the CommonJS scheme, which imports modules via require and defines the module's output interface via module.exports. This module loading solution is a server-side solution that introduces modules in a synchronous manner. Since files on the server side are stored on local disk, it is very fast to read, so it is no problem to load modules in a synchronous manner. However, on the browser side, asynchronous loading is more appropriate because the module is loaded using a network request. The second is THE AMD scheme, which adopts the asynchronous loading mode to load the module. The loading of the module does not affect the execution of the following statements. All statements that depend on the module are defined in a callback function, and the callback function is executed after the loading is complete. Require.js implements the AMD specification. The third is CMD scheme, this scheme and AMD scheme are to solve the problem of asynchronous module loading, sea. Js implementation of CMD specification. It differs from require.js in how dependencies are handled in module definition and when dependent modules are executed. The fourth solution is proposed by ES6, which uses the form of import and export to import and export modules. This scheme is different from the three above. Refer to 61.Copy the code

65. What are the differences between AMD and CMD specifications?

The main differences are twofold. (1The first is the different treatment of dependencies when modules are defined. AMD advocates dependency preloading, declaring the module it depends on when defining a module. CMD advocates proximity only when a module is usedrequire. (2The second aspect is that the execution timing of dependent modules is handled differently. First of all, BOTH AMD and CMD load modules asynchronously, but the difference lies in the execution timing of modules. AMD executes dependent modules directly after the completion of the loading of dependent modules, and the execution order of dependent modules may not be consistent with our written order. And CMD does not execute after the dependency module is loaded, just download, wait until all the dependency module is loaded, enter the callback function logic, encounteredrequireStatement, so that modules are executed in the same order as we wrote them.// CMD
 define(function(require.exports.module) {
  var a = require('./a')
  a.doSomething()
  // Omit 100 lines here
  var b = require('./b') // Dependencies can be written nearby
  b.doSomething()
  // ...
 })

 // AMD recommended by default
 define(['./a'.'./b'].function(a, b) { Dependencies must be written in the beginning
  a.doSomething()
  // Omit 100 lines here
  b.doSomething()
  // ...
 })
Copy the code

For more information, see “Front-end modularity, THE Difference between AMD and CMD”.

66. Differences between ES6 module and CommonJS module, AMD, CMD.

(1) CommonJS module outputs a copy of the value, ES6 module outputs a reference to the value. The CommonJS module outputs a copy of the value, meaning that once a value is output, changes within the module do not affect that value. ES6 modules operate differently from CommonJS. When the JS engine statically analyzes a script, it generates a read-only reference to the module load command import. When the script is actually executed, it will be evaluated in the loaded module based on the read-only reference. (2) CommonJS module is run time load, ES6 module is compile time output interface. A CommonJS module is an object, which loads the entire module on input, generates an object, and then reads methods from that object. This loading is called "runtime loading." An ES6 module is not an object, and its external interface is a static definition that is generated during the code static parsing phase.Copy the code

67. What is the core principle of requireJS? How does it load dynamically? How to avoid multiple loads? How is it cached?

The core principle of require.js is to introduce modules asynchronously by dynamically creating script scripts, and then listen for the load event of each script. If each script is loaded, the callback function will be called.Copy the code

For more information, please refer to: requireJS usage and Principle Analysis. What is the core principle of requireJS? Analysis of Script Loading Principle from RequireJs Source Code RequireJs Principle Analysis

68. JS module loader wheel how to build, that is, how to implement a module loader?

For details, please refer to: “How does JS module loader load principle?”

“ECMAScript6” “ECMAScript6” “ECMAScript6”

In my opinion, ES6 added classes to complement some of the object-oriented language features missing from JS, but in essence it is a syntactic sugar, not a new thing, and the idea behind it is archetypal inheritance. Adding a class helps us organize our code better. Methods added to a class are actually added to the prototype of the class.Copy the code

See: ECMAScript 6 implements Class, What does it Mean for JavaScript Front-end Development? Basic Syntax of Class

70. What’s the difference between documen.write and innerHTML?

The contents of Document.write will replace the entire contents of the document, rewriting the entire page. The innerHTML content replaces only the content of the specified element and overwrites only part of the content of the page.Copy the code

For more information, see “The Difference between Document.Write and innerHTML”.

71. DOM manipulation – How to add, remove, move, copy, create, and find nodes?

1CreateDocumentFragment (node) createElement(node) createTextNode(text) (2AppendChild (node) removeChild(node) replaceChild(new,old)
     insertBefore(newThat (old)3) find getElementById() getElementsByName() getElementsByTagName() getElementsByClassName() querySelector() QuerySelectorAll (),4Attribute operation getAttribute(key) setAttribute(key,value) hasAttribute(key) removeAttribute(key)Copy the code

For more information, please refer to “DOM Overview”, “DOM Operation summary of Native JavaScript”, and “DOM node related API collection in Native JS”.

72. The difference between innerHTML and outerHTML?

For such an HTML element: <div> Content <br/></div>. InnerHTML: the innerHTML, content<br/>; OuterHTML: External HTML, <div>content<br/></div>; InnerText: the innerText, content; OuterText: Internal text, content;Copy the code

73.. What is the difference between call() and.apply()?

They do exactly the same thing, except for the form of the arguments passed in. Apply takes two arguments. The first argument points to the this object in the function body. The second argument is a set with an underlying index, which can be an array or an array of classes. Call takes a variable number of arguments. Like apply, the first argument represents the "this" in the function, and each argument is passed to the function from the second argument.Copy the code

For more information, please refer to “Differences and Uses of Apply and Call”.

74. JavaScript class array object definition?

An object with a length attribute and several index attributes can be called an array-like object, which is similar to an array but cannot call array methods. Common array-like objects include arguments and the return results of DOM methods, and a function that can also be considered an array-like object because it has the length property value, representing the number of arguments that can be accepted. Common types of arrays into there are several ways of: (1) through the call call slice method to realize the transformation of an Array of Array. The prototype. Slice. Call (arrayLike); (2) through the call call splice method to realize the transformation of an Array of Array. The prototype. The splice. Call (arrayLike, 0); (3) through the apply calls the Array concat method to implement the conversion Array. The prototype. Concat. Apply ([], Array.from(arrayLike); array. from(arrayLike);Copy the code

For more information, please refer to “JavaScript Depth array Objects and arguments”, “JavaScript Class Array”, “Understanding JavaScript Class Array”.

75. What are the native methods for arrays and objects?

Conversion methods for arrays and strings: toString(), toLocalString(), Join () where join() can specify a separator when converted to a string. The end-of-array manipulation methods pop() and push(), which can take multiple arguments. The reverse() and sort() methods, which are reordered by shift() and unshift(), and the sort() method can pass in a function to compare the two values, and if the value returned is positive, swap the two arguments. Concat () returns a concatenated array without affecting the original array. Slice (), used to slice a portion of an array without affecting the original array. The array insertion method splice(), which affects the index of the original array to find a particular item, IndexOf() and lastIndexOf() iteration methods Every (), some(), filter(), map(), and forEach() array merging methods Reduce () and reduceRight()Copy the code

For more information, see: Array Types in JavaScript

76. Array fill method?

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Does not include terminating indexes. The fill method takes three arguments: value, start, and end. The start and end arguments are optional and default to 0 and the length value of this object, respectively.Copy the code

For details, see array.prototype.Fill ().

77. [,] length?

The trailing comma (sometimes called the "terminating comma") is useful for adding elements, parameters, and attributes to JavaScript code. If you want to add a new attribute and the previous line already uses a trailing comma, you can simply add the new line without modifying the previous line. This makes version control clearer and code maintenance less troublesome. JavaScript initially supported trailing commas in array literals, and later added trailing commas to object literals (ECMAScript 5). More recently (ECMAS cript 2017), it was added to function parameters. JSON, however, does not support trailing commas. If more than one trailing comma is used, a gap occurs. Arrays with gaps are called sparse arrays (compact arrays have no gaps). The length of a sparse array is a comma.Copy the code

For more information, please refer to “The Last Comma”.

78. Improved scope and variable declarations in JavaScript?

The expression of variable promotion is that wherever we declare a variable in the function, it seems to be promoted to the head of the function, which we can access without error before the variable declaration. The essence of variable declaration enhancement is that js engine has a parsing process before code execution, creating execution context and initializing some objects that need to be used during code execution. When we visit a variable, we can be carried to the current context to look up the scope chain, and the first end of the scope chain point to is the variable object of the current execution context, the variable object is an attribute of the execution context, which contains the function parameter, all function and variable declarations, the object is in the code when the parsing. This is the root cause of the variable declaration enhancement.Copy the code

For more information, see JavaScript in Depth with Variable Objects.

79. How to write high-performance Javascript?

(1) Use bit operation instead of some simple four operations. (2) Avoid using too deep nested loops. (3) Do not use undefined variables. (4) When you need to access the length of the array for many times, you can use variables to save it, to avoid going to the attribute search every time.Copy the code

For more information, see: How to Write High-performance Javascript?

80. A brief introduction to the V8 engine garbage collection mechanism

V8's garbage collection mechanism is based on generational collection, which in turn is based on the generation hypothesis, which has two characteristics: new objects tend to die early, and undead objects tend to live longer. Based on this hypothesis, v8 divides memory into the new generation and the old generation. Objects that are newly created or that have only undergone a garbage collection once are called the new generation. An object that has been garbage collected multiple times is called an old generation. The new generation is divided into "From" and "To", and "To" is generally idle. Recycle garbage by executing the Scavenge algorithm when the From space is full. The application logic will stop when we run the garbage collection algorithm and continue when the garbage collection is complete. This algorithm is divided into three steps: (1) First check the surviving object of From space, if the object is alive, judge whether the object meets the condition of promotion to the old generation, if it meets the condition, it will be promoted to the old generation. If the condition is not met, move To space. (2) If the object does not survive, the space of the object is freed. (3) Finally, the roles of From space and To space will be exchanged. The exploiture is based on two conditions. The first is to determine whether the object has been screcycled. If so, copy the object From the From space to the old generation; If not, it is copied To the To space. (2) The second is whether the memory usage ratio of To space exceeds the limit. When an object is copied From the From space To the To space, if the To space usage exceeds 25%, the object is promoted directly To the old generation. The reason for setting 25% is that after the algorithm ends, the two Spaces will switch positions. If the memory of the To space is too small, the subsequent memory allocation will be affected. In the old generation, mark elimination method and mark compression method were used. Mark purge first marks the objects that are alive in memory, and then purges those that are not. Since tag clearing will cause a lot of memory fragmentation, it is not convenient for later memory allocation. Therefore, to solve the problem of memory fragmentation, mark compression method is introduced. Because the application logic will be suspended during garbage collection, the time of each pause will not be long for the new generation method due to the small memory, but for the old generation, the time of each garbage collection will be long, and the pause will cause a great impact. V8 addresses this problem by introducing incremental markers, which break a pause into multiple steps, each one of which allows the execution logic to run for a while, and so on.Copy the code

For more information, see: An In-depth Understanding of V8 garbage Collection, Garbage Collection in JavaScript

81. What operations cause memory leaks?

Related knowledge:

(1) unexpected global variables (2) forgotten timers or callback functions (3) out-of-dom references (4) closuresCopy the code

Answer:

The first is when we accidentally create a global variable by using an undeclared variable, leaving it in memory and unable to reclaim it. The second case is that we set the setInterval timer and forget to cancel it. If the loop function has a reference to an external variable, that variable is left in memory and cannot be reclaimed. The third case is when we get a reference to a DOM element that is deleted and cannot be retrieved because we keep the reference to the element. The fourth case is improper use of closures, resulting in some variables being left in memory.Copy the code

For details, please refer to: “JavaScript Memory Leak Tutorial”, “4 Types of JavaScript Memory Leak and How to avoid it”, “Prevent the occurrence of four types of MEMORY Leak in JS”, “Typical JavaScript Memory Leak and Chrome troubleshooting methods”.

82. Requirements: Implement a site that does not refresh the entire page and responds correctly when the browser moves forward and backward. Give your technical implementation plan?

Using pushState + Ajax to enable the browser to move forward and backward without refreshing, we add a state record to the history object after a successful Ajax call. A state record contains the URL, title, and Content properties. This state object can be retrieved in the POPState event, and we can pass data using content. Finally, we respond to the browser's forward and backward actions by listening for the window. onpopState event. We can use replaceState to replace the records of the home page. We can also use replaceState to replace the records of the home page. When a page is refreshed, it still requests data from the server. So if the requested URL requires the cooperation of the back end to redirect it to a page.Copy the code

Manipulating the Browser History: pushState + Ajax Moving Forward and Backward without Refreshing

83. How do I determine whether the script is currently running in a browser or node environment? (ali)

this === window ? 'browser' : 'node'; Check whether the Global object is window. If not, the script is not running in the browser.Copy the code

84. What is the difference between placing the script tag before and after closing the body at the bottom of the page? How will the browser parse them?

See “Why put a Script tag after the body tag and before the HTML tag” for more information. How to load resources in a Browser

85. How long is the delay of click events on mobile terminals, and why? How to solve this delay?

The reason why there is a 300ms delay for a mobile click is that there will be a double click on the mobile, so the browser will have to wait 300ms after click to see if the user has a next click to determine whether the action is a double click. There are three ways to solve this problem: (1) Disable zooming with meta tags. (2) Set the viewPort of the web page to the Ideal ViewPort via the Meta tag. (3) Call some JS libraries, such as FastClick click delay can also cause click penetration problems, that is, if we register the touchStart listening event on an element, this event will hide the element, we find that when the element is hidden, Trigger a click event for an element below this element, which is called click penetration.Copy the code

For more information: click Delay and Click Penetration on Mobile 300ms

86. What is “front-end routing”? When is it appropriate to use “front-end routing”? What are the advantages and disadvantages of front-end routing?

(1) What is front-end routing? Front-end routing is to assign the task of different routes corresponding to different contents or pages to the front-end, which was realized by the server returning different pages according to the different URL. (2) When to use front-end routing? (3) What are the advantages and disadvantages of front-end routing? Advantages of good user experience, do not need to capture all from the server, and every time a quick show weakness to users Single page not remember before the position of the scroll, not in advance, to remember the location of the rolling back Front-end routing a total of two kinds of implementations, one kind is through the way of the hash, one kind is through the use of pushState.Copy the code

Detailed information can refer to: “What is the” front-end routing “” Talking about front-end Routing” “What is front-end routing?”

87. How do I test front-end code? Do you know BDD, TDD, Unit Test? Know how to test your front-end engineering (Mocha, Sinon, Jasmin, qUnit..) ?

For details, please refer to: Brief Introduction to Front-end Unit Testing.

88. What are the ways to check the browser version?

There are two ways to check the browser version: Is a kind of detection window. The navigator. UserAgent value, but this way is not reliable, because the userAgent can be changed, and early browsers such as ie, The server can avoid detection by disguising the value of its userAgent to Mozilla. The second method is function detection, judging according to the unique characteristics of each browser, such as the unique ActiveXObject under IE.Copy the code

For more information, see JavaScript To Determine Browser Types.

89. What is Polyfill?

Polyfill refers to code that implements native apis that are not supported by browsers. For example, querySelectorAll is a native Web API that many modern browsers support, but some older browsers don't, so if someone writes a code to implement it and those browsers support it, then this would be a Polyfill. A SHIm is a library with its own API, rather than simply implementing an API that is not supported natively.Copy the code

For more information, see: “Jargon” in Web Development, “What is Polyfill?”

90. Use JS to get file extensions?

   function getFileExtension(filename) {
     return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
   }

   StringThe.lastIndexof () method returns the specified value (in this case'. ') the last position in the string in which the method was called, or - if not found1. for'filename''.hiddenfile', the return values of lastIndexOf are respectively0And -1The unsigned right-shift operator (>>>) will -1convert4294967295, -2convert4294967294, this method ensures that the file name stays the same in the edge case.String.prototype.slice() extracts the file extension from the index calculated above. If the index is larger than the length of the filename, the result is"".Copy the code

For more information, see “How to Get File extensions More efficiently”.

91. Introduce js throttling and anti – shake?

Related knowledge:

Function stabilization: Execute the callback n seconds after the event is triggered. If the event is triggered again within n seconds, the timer is reset. Function throttling: Specifies a unit of time within which only one event callback can be executed. If an event is triggered multiple times within the same unit of time, only one event can take effect. Function anti - shake implementationfunction debounce(fn, wait) {
   var timer = null;

   return function () {
     var context = this,
       args = arguments;

     // If there is a timer, cancel the previous timer and reset the time
     if (timer) {
       clearTimeout(timer);
       timer = null;
     }

     // Set the timer so that the event interval is executed after the specified event
     timer = setTimeout(() = >{ fn.apply(context, args); }, wait); }} function throttling implementationfunction throttle(fn, delay) {
   var preTime = Date.now();

   return function () {
     var context = this,
       args = arguments,
       nowTime = Date.now();

     // If the interval exceeds the specified time, the function is executed.
     if (preTime - nowTime >= delay) {
       fn.apply(context, args);
       preTime = Date.now(); }}}Copy the code

Answer:

Function stabilization means that the callback is executed after the event is triggered for n seconds. If the event is triggered again within n seconds, the timer is reset. This can be used on some click-request events to avoid sending multiple requests to the back end because the user clicks multiple times. Function throttling refers to the specified unit of time. Within this unit of time, only one callback function that triggers an event can be executed. If an event is triggered multiple times within the same unit of time, only one callback function can take effect. Throttling can be used to reduce the frequency of event calls through event throttling on scroll function event listeners.Copy the code

For more information, please refer to: easy to understand JS function throttling and function anti-shake, JavaScript event throttling and event Anti-shake, JS Anti-shake and Throttling.

92.object.is () differs from the original comparison operators’ === ‘and’ == ‘?

Related knowledge:

The two equal signs are equal, and the type conversion is performed during comparison. Trisomes are equal (strict), no implicit type conversion is performed when comparing (false is returned if the type is different). Object. Is deals specifically with NaN, -0, and +0 on the basis of the equality of the three equal signs, ensuring that -0 and +0 are no longer the same, but object. is(NaN, NaN) returns true. It should not be used as looser or stricter than other equivalents.Copy the code

Answer:

When the double equal sign is used for equality judgment, if the types of the two sides are inconsistent, forced type conversion is performed before comparison. If the two sides of an equal sign are inconsistent, false is returned instead of mandatory type conversion. When using object. is for equality, it is generally the same as for trisomes. It handles special cases where -0 and +0 are no longer equal and two nans are assumed to be equal.Copy the code

93. The escape, encodeURI, what is the difference between encodeURIComponent?

Related knowledge:

Escape and encodeURI both belong to percent-encoding. The basic function of escape and encodeURI is to convert illegal URI characters to valid characters in a format similar to %*. The fundamental difference is that escape processes characters other than 0xFF by prefacing the unicode of the character with a "%u", whereas encode URIs do UTF-8 and then prefacing each byte code of UTF-8 with a "%". When dealing with characters up to 0xFF, the encoding is the same (both "%X X", where XX is the hexadecimal Unicode for characters and also utF-8 for characters), but the range (which characters are encoded and which are not) is different.Copy the code

Answer:

EncodeURI escapes the entire URI, converting illegal characters in the URI to legal characters, so characters that have special meaning in the URI are not escaped. EncodeURIComponent escapes URI components, so special characters can be escaped as well. Escape and encodeURI have the same effect, but they are different for unicode encoding characters other than 0xFF. Escape prefixes the character's Unicode encoding with %u, EncodeURI first converts characters to UTF-8 format and prefixes each stanza with %.Copy the code

Details you can refer to: “what is the difference between the escape, encodeURI, encodeURIComponent?”

94. The relationship between Unicode and UTF-8?

Unicode is a collection of characters that can now hold more than a million characters. Each character corresponds to a different Unicode code, which only specifies the binary code of the symbol, but does not specify how the binary code is encoded and transmitted in the computer. Utf-8 is an encoding of Unicode. It is a variable-length encoding that can represent a character in 1 to 4 bytes.Copy the code

For more information, please refer to: Detailed Character Encodings notes on Character Encodings: ASCII, Unicode, and UTF-8.