preface

Summary of many common JS basic knowledge points, most of the articles on the network have seen a time. Planning again, there is no answer to any question, most of their search from the nuggets of quality articles. Because they are all piecemeal questions, looking for too many or roughly the same questions. Also take into account what copyright problem, hope forgive me! Hee hee lay a good foundation for his junior internship! Oneself must refuel!! Also sorted out for children in need ✨

JS based

1. The basic data type of js (value type).

ES6 and before (5 types)

String, Number, Boolean, Null, Undefined

After ES6 before ES10 (6 types)

String, Number, Boolean, Null, Undefined, Symbol

After ES10 (7 types)

String, Number, Boolean, Null, Undefined, Symbol, BigInt

2. Complex data types of JS (reference types).

Object, Array, Function

3. Js has several types of values

Stack: Basic data type

Heap: Reference data type

Differences between the two:

1. Different memory locations are different when declaring variables:

The value of the primitive data type variable is stored on the stack because the space occupied by the primitive data type is fixed and therefore directly accessible.

Reference data types stored on the stack are address Pointers to variables that point to references in the heap. Because the size of the reference data type changes, not being able to store it on the stack affects the speed of lookups.

2. Different access mechanisms:

Js does not allow you to access variables stored in the heap directly. Instead, you can access the address in the heap, and then access the reference type according to the address

The data variables in the stack are directly accessible.

3. Different when copying variables:

Variables in the stack copy values as another copy, independent of each other.

Objects in the heap copy by assigning a variable that holds the memory address to another variable. Both reference the same address, and any change in either variable changes the other variable.

4. Different parameter passing:

Passing a parameter is passing the value of a variable to the parameter. The value in the reference data type is the address of the variable in heap memory.

So when you pass a reference data type as a parameter, making changes to the variable inside the function affects the value of the reference data outside the function.

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

concept

The concept of stacks and heaps comes from data structures and operating systems.

In the data structure, the stack is a first-in-last-out queue, while the heap is a priority queue, and the binary tree is a typical heap queue.

Distinction and connection

Application way

  1. Heap: applied for and sized by the programmer himself
  2. Stack: Automatically allocated by the system

Apply size limits

  1. Heap: a data structure extending from low address to high address. It is a discontinuous area of memory. This is because the system uses a linked list to store free memory addresses, which is naturally discontinuous. The size of the heap is limited by the amount of virtual memory available in the computer system. Thus, the heap is more flexible and larger.

  2. Stack: Under Windows, a stack is a data structure that extends from high to low addresses. It is a contiguous area of memory. The address at the top of the stack and the maximum size of the stack are specified by the system. Under WINDOWS, the stack size is 2M (or 1M). If the stack size exceeds the available space, overflow will be prompted. Therefore, less space can be obtained from the stack.

Apply for efficiency

  1. Heap: Allocation of memory by a mechanism like New is generally slow and prone to fragmentation, which can be explained by the allocation mechanism, but is easier to use.

  2. Stack: automatically allocated by the system, relatively fast, and programmers are out of control.

timeliness

  1. Heap: Persistent
  2. Stack: temporary

Context call

  1. Pile: a global

  2. Stack: local

memory

  1. Stack area memory – automatically released by the compiler. It mainly stores function parameters, local variables, etc., and is destroyed when finished.

  2. Heap memory – it is mainly released manually by the programmer. If it is not released manually, the garbage collection mechanism will collect it.

5. What is the internal attribute [[Class]]

All variables returned as object by Typeof have an internal attribute [[Class]], which can be regarded as an internal classification

Use the Object. The prototype. ToString. Call () returns the classification.

Such as the Object. The prototype. ToString. Call ([]) returns * * [[Object Array]] * *

6. Describe the built-in objects of JS

Built-in objects in JS refer to global value properties, function objects, and instantiable constructors that exist in global scope and are defined by JS prior to operation.

Global value properties such as NaN, NULL, etc., functions such as parseInt, parseFloat, etc

The constructors Number, Boolean, Function, etc. can be instantiated for other objects as well as Date, Math object Math, etc.

7. Use of undefined and undeclared

  1. A variable declared globally but not yet assigned returns undefined
  2. Undeclared variables are undeclared. Is not defined is returned with an error.

8. Null vs. undefined

First, null and undefined are both basic data types.

  1. Undefined means a variable is undefined, and null means an empty object

  2. Undefined is returned when a variable is undefined. Null is used as the initial value of the variable object (similar to a placeholder).

  3. Typeof NULL returns object.

  4. Null == undefined returns true, but three equals signs return false.

9. How to obtain the safe value of undefined

Reason: undefined is an identifier, so it can be used and assigned as a variable, but this will affect the normal judgment of undefined.

Idea: the expression void ___ returns no value, so undefined is returned.

Result: void does not change the result of the expression, only that the expression does not return a value.

Use void 0 to get undefined.

! [image-20200928155305342](/Users/lin/Library/Application Support/typora-user-images/image-20200928155305342.png)

10. A few basic conventions for writing JavaScript

Following some basic guidelines is good for reading and maintenance

  1. The variable declaration should always precede the scope, and the var declaration should always give the initial value.
  2. Use ‘= = =’ and ‘! ==’ instead of ‘==’ and ‘! = ‘.
  3. Do not add methods to the prototype objects of built-in objects, such as Array, Object, Function, etc.
  4. Constants such as address and time in code are replaced by variables.
  5. The switch statement must have a default branch.
  6. If and for statements should have braces.

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

In JavaScript we use constructors to create an instance object

Inside each constructor is a Prototype property, which is an object => prototype object

The proto property inside the instance object refers to the prototype of the constructor and can be viewed as an instance of any other constructor. The proTO property chain is the prototype chain.

When we want to find an attribute or method on the instance Object, if the instance Object does not have one, we can look up the proto attribute level by level until Object.prototype.

Features: JavaScript is passed by reference, and when we modify the properties of a stereotype, all inheritance is modified.

12. JavaScript methods for getting prototypes

function R(){} let one=new R();

  1. console.log(Object.getPrototypeOf(one)); // Official recommendation
  2. console.log(one.proto);
  3. console.log(one.constructor.proto);

13. The representation of different base numbers in JS

  1. The values starting with 0X and 0X are hexadecimal
  2. The values starting with 0O and 0O are in base 8
  3. The values starting with 0B and 0B are base 2

14. What is the safe range of integers in js

A safe integer means that the accuracy of the integer is not lost when it is converted to binary.

The maximum value is 2 to the 53rd power of -1, and calculations beyond the safe integer range are subject to error.

In ES6, they are defined as number. MAX_SAFE_INTEGER and number.min_safe_INTEGER. Returns infinity when the integer range is exceeded.

15. What is the result of typeof NaN

  1. Typeof NaN returns number.
  2. NaN is a special value that is not equal to itself. NaN! =NaN => true

16. Differences between isNaN and Number.isNaN functions

When isNaN receives a parameter, it tries to convert it to a numeric value

So incoming values that cannot be converted to a value return true, but non-numeric values also return true, affecting NaN’s judgment.

Number.isNaN determines whether it is Number first and then isNaN determines. Judgment is more accurate.

17. How the Array constructor behaves when it has only one parameter value

The Array constructor has only one parameter value and treats it as the length value to create the Array, rather than as an element.

The resulting array is still empty, but with a preset length value.

18. Conversion rules for other 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 type, true to “true”, false to “false”.
  3. Values of type Number are converted directly, but very small and very large numbers are used in exponential form.
  4. Values of type Symbol are converted directly, but only explicit casts are allowed. Using implicit casts produces errors.
  5. Defined for ordinary objects, 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.

19. Conversion rules for other values to numeric values

  1. Undefined returns NaN.

  2. Null returns 0.

  3. True returns 1, false returns 0.

  4. Converting a string value to a numeric value is like using Number(); NaN is returned if the string contains a non-numeric value, and 0 is returned if the string is empty.

20. Rules for converting other values to Boolean values

There are six types of conversion to false:

Null, undefined, false, “”, NaN, +0, -0

The rest is true

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

  1. ValueOf of {} is **{} and toString is [Object Object]**

  2. [] valueOf is **[], toString is “”**

22. What is a false value object?

In some cases, the browser creates some objects on top of some regular JS

These objects are false when cast to a Boolean value

For example, document.all is a pseudo-array representing an array of all elements in the page, which is provided by the DOM to JS for use.

23. What does the ~ operator do?

  1. ~ indicates that the value is reversed by bit
  2. ~~ can be used to round

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

  1. Numbers in parsed strings are allowed to contain non-numbers. For example, parseInt parses a string to return the beginning of a number, or NaN if the first character is a non-number
  2. The type conversion Number () cannot parse a string with invalid characters. Otherwise NaN is returned.

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

  1. When at least one of the preceding and following variables of the + operator is a string, they are concatenated with +.
  2. If both are numbers, digit addition is performed.
  3. With the exception of +, if one of the operators is a number, the other converts to a number.

26. When can implicit casts of Booleans occur?

When a conditional statement is judged

Examples are if statements that are converted to booleans, and while statements. Three expressions. For (; 😉 The second term in. Logical operators | | and && for judgment.

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

  1. A Boolean cast is performed on the first item.
  2. Using the | | operator, when the first is true, is directly returns true, when the first item is false, it returns the second Boolean value
  3. The && operator returns the Boolean value of the second item when the first item is true, or false when the first item is false.

28. Cast Symbol value?

  1. The symbol value can be converted explicitly but cannot be converted implicitly and an error is reported.
  2. The symbol value cannot be converted to a numeric type, but can be converted to a Boolean value, either explicit or implicit, true.

29. Cast rules for the == operator?

  1. When a string is compared with a numeric type, the string is converted to a numeric type and then compared.
  2. When comparing other types with booleans, the Boolean value is converted to a numeric value before any other comparison is performed.
  3. NaN and itself are false when ==
  4. Null == undefined is true
  5. If both operation values are objects, you need to compare whether they are the same reference object.

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

  1. Use the Number () method, but only if the contained string does not contain illegal characters.
  2. The parseInt () method is rounded.
  3. ParseFloat () method, floating point number
  4. Implicit type conversion

31. 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”?

Use the regular expression method

function format(number){ return number && number.replace(/(\d)(? =(\d{3}+\.) )/g, function($1, $2, $3){ return $2 + ','; })}Copy the code

? =pattern indicates the character that matches the beginning of pattern, such as window(? = 95 | 98 | | 2000 xp), can match to the window in the window2000.

32. Various methods for generating random numbers?

Math.random()

33. How to implement random array sort

  1. Randomly extract an array element into a new array:

    function randomsort(arr){  
    	var newarr = [];  
      while(arr.length > 0) {var index = Math.floor(Math.random()*arr.length);   
        newarr.push(arr[index]);   
        arr.splice(index, 1);  
      }  
      return newarr; 
    }
    Copy the code
  2. Swap the elements of an array randomly (shuffle)

function randomsort(arr){  
  var temp,  leng = arr.length,  tempindex;  
  for(var i = 0; i < leng; i++){  
    tempindex = Math.floor(Math.random()*(leng - i) + i);  
    temp = arr[i];  
    arr[i] = arr[tempindex];  
    arr[tempindex] = temp;
  }  
  return arr; 
}
Copy the code

34. How many ways can javascript create objects?

// 1. The most straightforward way: create a literal pattern
let obj = {
  name: 'much'.age: 20.sex: 'male'
}

// 2. Call system constructor to create
let obj = new Object()
obj.name = 'much'
obj.age: 20,
obj.sex: 'male'

// 3. Factory mode creation
function createPerson(name, age, sex){
  let p = new Object(a); p.name = name; p.age = age; p.sex = sex; }var person1 = createPerson("1" greatly.20.'male');
var person2 = createPerson("Greatly 2".18.'male');

// 4. Create a custom constructor
function Person(name, age, sex){
  this.name = name;
  this.age = age;
  this.sex = sex;
}
var person1 = new Person("1" greatly.20.'male');
var person2 = new Person("Greatly 2".18.'male');
/** There are several differences between this method and factory creation: 1. The function name Person is uppercase, while the factory creation function creatPerson is lowercase. 2. This method does not have a return statement, but the factory function creates a return; 3. This method assigns attributes and methods directly to this object, which does not appear in factory mode; 4. This method instantiates an object through the new operator, whereas the factory mode instantiates an object by calling a function directly. * * /

// 5. Create objects in prototype mode
function Person(name, age, sex){
  this.name = name;
  this.age = age;
  this.sex = sex;
}
var person1 = new Person("1" greatly.20.'male');
var person2 = new Person("Greatly 2".18.'male');
Copy the code

35. How many ways to implement JS inheritance?

  1. Stereotype chain inheritance: if we point the child constructor’s stereotype object to the parent constructor’s instance object, the child constructor’s instance object can inherit the attributes and methods of the parent class. The disadvantages are that subclasses cannot be created with parameters passed to the parent class, and all reference types on the parent class prototype can be applied to all instance objects.

    function Father(name, age){  
      this.name = name;  
      this.age = age; 
    } 
    Father.prototype.getName = function(){  
      return this.name;
    } 
    function Child(skill){  
      this.skill = skill; 
    } 
    Child.prototype = new Father('zhangsan'.20); 
    var child = new Child('dance'); 
    console.log(child.getName());
    Copy the code
  2. Constructor inheritance: called by using the call method on the parent constructor in a subclass, and modifying the this pointer to point to the subclass while passing arguments. Advantages: Avoids reference type attributes being shared by all instances, and solves the problem of not being able to pass parameters. The downside is that methods are defined in constructors, so they have to be created every time an instance is created.

    function Father(name, age){  
      this.name = name;  
      this.age = age;  
      this.getName = function(){   
        return this.name;
      }  
      this.getAge = function(){   
        return this.age; }}function Child(name, age, skill){  
      Father.call(this, name, age);  
      this.skill = skill 
    } 
    var child = new Child('zhangsan'.20.'dance'); 
    console.log(child.getName())
    Copy the code
  3. Composite inheritance: by combining stereotype chain inheritance and constructor inheritance.

    function Father(name, age){  
      this.name = name;  
      this.age = age; 
    } 
    Father.prototype.money = function(){  
      console.log('100000'); 
    } 
    function Child(name, age, skill){  
      Father.call(this, name, age);  
      this.skill = skill; 
    } 
    Child.prototype = new Father(); 
    Child.prototype.constructor = Child; 
    Child.prototype.exam = function(){  
      console.log('i want to have an exam');
    } 
    var child = new Child('zhangsan'.20.'dance'); 
    console.log(child.money())
    Copy the code
  4. Primitive inheritance: Objects passed in as parameters are used as prototypes to create objects.

    function creatObj(o){  
      function F(){};  
      F.prototype = o;  
      return new F(); 
    } 
    var person = {  
      name: 'zhangsan'.age: 20 
    } 
    var person1 = creatObj(person); 
    var person2 = creatObj(person); 
    person1.name = 'lisi'; 
    console.log(person1.name, person2.name);
    Copy the code
  5. Parasitic inheritance

    function Father(name, age){  
      this.name = name;  
      this.age = age; 
    } 
    function Child(name, age){  
      Father.call(this, name, age); 
    } (function(){  
      var Super = function(){};  
      Super.prototype = Father.prototype;  
      Child.prototype = new Super(); 
    })() 
    Child.prototype.constructor = Child; 
    var child = new Child('Tom'.20); 
    console.log(child.name)
    Copy the code

What is a prototype?proto, a constructor? Javascript’s scope chain?

  1. What are prototype, proto, constructor?

    1. __proto__ is a prototype property, an object specific property that refers to another object (the prototype object of point 2), usually an instance property such as arr. Proto
    2. Prototype is the object to which the constructor points, such as array.prototype
    3. Constructor is a prototype object used to refer to back to the constructor properties, is an object pointer to function, such as Array. The prototype. The constructor
  2. A scope chain is an ordered list pointing to variable objects that guarantees ordered access to them when a function is executed

    The variable object contains all the variables and functions in the executing function. We can find the variables and functions of the external function through the scope chain

    When we execute a function, we look for variables in the execution context first, and if not, we look up the scope chain until we look for global variables in the global context.

38. Talk about the understanding of This object.

This is an attribute in the function execution context that points to the object on which the function was last called.

  1. When a function is called, if the function is not an object property, this refers to the global object when it is called.
  2. When a method is called, this refers to the object in which the method is called.
  3. When a function is created with new through the constructor, an instance object is created before execution. The function’s this refers to the instance.
  4. Change the this orientation of a function by using call, apply, and bind
    1. The call method takes the first argument to change the object to which this points and the subsequent arguments to pass
    2. The difference between Apply and Call is that the parameters passed are arrays
    3. The bind method differs from call and apply in that it does not call the function immediately. It first binds the function to this, returns the new function with the this pointer changed, and calls it when it is ready to execute. The this pointer to this function does not change except by using the new constructor.

Priority: Of the four patterns, the use of the new constructor has the highest priority, followed by call, apply, bind calling functions, then the method call pattern, and finally the function call pattern.

39. What does Eval do?

The eval method parses and executes the passed character in JS syntax.

Eval syntax should be avoided as much as possible because it is non-performance consuming, parsing JS syntax the first time and executing JS statements the second time.

// Wrap an eval method
function eval(fn) {
  // a variable pointing to Function prevents some front-end compilation tools from reporting errors
  const Fn = Function
  return new Fn('return ' + fn)()
},
Copy the code

40. What is DOM and BOM?

  1. DOM is the document object model, which views a document as an object that defines its methods and interfaces. In the DOM, the various components of a document can be obtained through Object.attribute, and the root Object is Document.
  2. BOM is the browser object model, which views the browser as an object that defines the browser’s methods and interfaces. In addition to the document component, it can also access the browser window component, such as the navigator, history, and so on.

41. Write a generic event listener function.

// event(event) toolset
markyun.Event = {
    // After the page is loaded
    readyEvent : function(fn) {
        if (fn==null) {
            fn=document;
        }
        var oldonload = window.onload;
        if (typeof window.onload ! ='function') {
            window.onload = fn;
        } else {
            window.onload = function() { oldonload(); fn(); }; }},/ / sight, respectively dom0 | | dom2 | | IE way to bind the event
    // Parameters: operation element, event name, event handler
    addEvent : function(element, type, handler) {
        if (element.addEventListener) {
            // Event type, function to execute, whether to capture
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent('on' + type, function() {
                handler.call(element);
            });
        } else {
            element['on'+ type] = handler; }},// Remove the event
    removeEvent : function(element, type, handler) {
        if (element.removeEventListener) {
            element.removeEventListener(type, handler, false);
        } else if (element.datachEvent) {
            element.detachEvent('on' + type, handler);
        } else {
            element['on' + type] = null; }},// Prevent events (mainly event bubbling, since IE does not support event capture)
    stopPropagation : function(ev) {
        if (ev.stopPropagation) {
            ev.stopPropagation();
        } else {
            ev.cancelBubble = true; }},// Cancel the default behavior of the event
    preventDefault : function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false; }},// 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, ensure that the event is always available;
    getEvent : function(e) {
        var ev = e || window.event;
        if(! ev) {var c = this.getEvent.caller;
            while (c) {
                ev = c.arguments[0];
                if (ev && Event == ev.constructor) {
                    break; } c = c.caller; }}returnev; }};Copy the code

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

  1. An event is an interaction between a user and a web page

    1. For example, mouse click event click, mouse movement event mousemove, etc
    2. In addition to user triggering, it can also be document loading, such as page scroll event scroll
    3. Events can be encapsulated into an event object, which contains all the information about the event object and the actions that can be performed on the event.
  2. Internet Explorer supports event bubbling, and Firefox supports both event models, event bubbling and event capture.

  3. Event. StopPropogation – Event. CancelBubble = true

43. What are the three event models?

An event is an interaction triggered by a user during page manipulation or by a browser. There are three event models.

  1. DOM0 event model, this event model does not have the concept of event flow, this model does not propagate, it can define listeners directly or through JS properties to define listeners.
  2. IE event model, this event model involves two event flows, execution stage and bubbling stage. The target event will be monitored and triggered at first, and then bubbling to the outermost document in turn. The nodes passing by will judge whether the event is bound or not, and trigger if there is. You can listen for events through attachEvent, and you can listen for multiple functions and execute them sequentially.
  3. DOM2 event model. This event model involves three event flows, namely capture stage, execution stage and bubble stage. The capture stage is propagated successively from document to check whether each node is bound with relevant events, if so, it will be triggered. The latter two are the same as the IE two phases. Events can be listened for via addEventListener, and the third parameter determines the order of capture and bubbling.

44. What is event delegation?

The essence of event delegation is to enable the parent node to listen for the events of the child node through event bubbling, thus generating event functions. That is, bind the listener function to the parent node of the child node, so that instead of binding the listener event to each child node, the parent node can be located to the child node target through the event object.

For example, when we dynamically create a child node, the dynamically created child node can also have listening events. We can bind the listening function to the parent node in the form of event delegate, which can reduce the consumption of memory.

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

Answer: [1, NaN, NaN].

The parseInt method converts the value to an integer and takes two arguments, val and radix. The radix value ranges from 2 to 36, and the value cannot be greater than the radix value so that the integer type is returned correctly.

The map method passes three parameters: value, index, and array. The third parameter is omitted by default.

ParseInt is passed 1-0, 2-1, 3-2. Since the value cannot be greater than the base, the last two items are returned as NaN. The first item defaults to 10 because the base is 0, and returns 1.

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

A closure is a function that has access to variables inside another function. For example, create another function inside a function, and the inner function can access variables that are local to the outer function.

Closure purpose:

  1. We can access the variables inside the function from outside the function, and we can call the closure function outside the function to get the variables inside the function.
  2. Another effect is to store a variable object in memory from the context of a function that has finished running. The closure function holds a reference to the variable object, so the variable object is not recycled.

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

Use strict means that JS statements are executed in strict mode.

It mainly eliminates some non-standard syntax, improves the efficiency of parsing and ensures the safe operation of the code.

Disallow the with statement, do not allow this to point to global objects, objects cannot have attributes with the same name, etc.

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

  1. Use the instanceof operator to determine whether the stereotype object of the object constructor appears somewhere on the stereotype chain.
  2. Object. The prototype. ToString. Call to return to the [[Class]] attributes.

49. The role of Instanceof?

The instanceof operator is used to determine whether the constructor’s prototype object is somewhere on the object prototype chain.

// Handwriting method
function instance(left, right){
    var proto = Object.getPrototypeOf(left);
    var prototype = right.prototype;
    while(true) {if(! proto)return false;
        if(proto === prototype){
            return true;
        }
        proto = Object.getPrototypeOf(proto); }}Copy the code

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

For the constructor, a new instance object is created by new, opening a new space in memory and pointing the instance object’s proto property to the constructor’s Prototype object.

And points the constructor property through this to the instance object created by new.

Determine the return value type of the function, return the created object if it is a value type, and return a reference type object if it is a reference type.

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

HasOwnProperty () method, which is used to look up properties of the object itself. Instead of looking up properties of the prototype, properties of the prototype will be ignored.

52. What do you know about JSON?

JSON is a lightweight text-based data interchange format that can be read and exchanged by any programming language.

In the development of the project, we often use JSON to transfer the data at the front and back ends. We convert the data into JSON string format and transfer it to the back end. After receiving the data, the back end processes it by converting it into a specific data structure.

JSON is based on THE JS syntax, but the two are quite different. JSON format is more strict, for example, method attributes cannot be used, and attributes are quoted.

Js provides two methods for manipulating JSON formats

  1. Json.stringify is the schema that converts JSON data structures into JSON strings.
  2. Parse converts JSON string format to JS data structure. If the received data is not in JSON string format, an error will be reported. For example, when we receive data in JSON string format at the back end, we can use json. parse to convert it to JS data structure for data processing.

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

We can in the console by () to obtain the corresponding element, similar to the document. The querySelectorAll () method. Math.random()(1<<24) indicates a random number between 0 and 2^24-1. ~~ indicates that the number is integer. ~~ indicates that the number is integer. ToSting (16) is an integer converted to hexadecimal.

54. What are the ways of js lazy loading?

Js code blocks the rendering of the page during parsing and execution, preventing THE DOM from executing downwards, so we want to delay js loading to make the page perform better and more smoothly. It is an optimization scheme

  1. By adding the defer attribute to the script tag, the top-down execution of the surface page will not block the downward execution of the page if the JS script is encountered. Instead, the JS script will be loaded and the page will be parsed at the same time. When all the page elements are parsed, the JS statements will be executed in the order of the JS script.
  2. You can add the async attribute to the script tag. The difference between the defer attribute and the JS script is that you wait until the JS script is loaded and then go back to execute the JS code instead of waiting until all the page elements are loaded. It is asynchronous and js steps are not executed in sequence.
  3. You can use timers to delay loading of JS scripts.
  4. Place the JS script at the bottom of the HTML page.
  5. We can use the way of dynamically creating script tags. We can monitor the loading event of the document, and then dynamically create script tags when all the page elements are loaded, so as to carry out the external chain of js scripts.

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

Ajax is asynchronous communication, where an XHR is created with XMLHTTPRequest, the data is retrieved from the server XML document, and updated locally to the page without refreshing the entire page.

function ajax(options){
   // Set the default object
    var defaults = {
        type: 'get'.url: ' '.data: {},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function(){},
        error: function(){}};// Merge the passed parameter object with the default object
    Object.assign(defaults, options);
    var params = ' ';
    for(var attr in defaults.data){
        params += attr + '=' + defaults.data[attr] + '&';
    }
    params = params.substr(0, params.length);
    if(defaults.type == 'get') {default.url = default.url + '? ' + params;
    }
    var xhr = new XMLHTTPRequest();
    xhr.open(defaults.type, defaults.url);
    if(defaults.type == 'post') {var contentType = defaults.headers['Content-Type'];
        xhr.setResquestHeader('Content-Type', contentType);
        if(contentType == 'application/json'){
            xhr.send(JSON.stringify(defaults.data));
        } else{ xhr.send(params); }}else {
        xhr.send();
    }
    xhr.onload = function(){
        var contentType = xhr.getResquestHeader('Content-Type');
        var responseText = xhr.responseText;
        if(contentType.includes('application/json')){
            responseText = JSON.parse(responseText);
        }
        if(xhr.status == 200){
            defaults.success(responseText, xhr);
        } else{ defaults.error(responseText, xhr); }}}Copy the code

56. What about browser caching?

The caching mechanism of the browser means that the browser can save a copy of the received Web resources for a certain period of time. If the browser makes the same request again within a valid event, the data will be directly retrieved from the cache without the request to the server. Effectively relieve the server side pressure and speed up the performance

Caching mechanisms can be divided into strong caching and negotiated caching.

Strong cache

During the cache validity period, resources can be fetched directly from the cache without making requests to the server.

The strong cache duration can be set by setting expries and cache-control in the HTTP header.

expries

The http1.0 attribute controls the cache validity time by setting the server side absolute time, but it has the disadvantage that the browser side and the server side may not be consistent, which leads to the cache validity time error.

cache-control

This can be done through cache-control in HTTP1.1, which provides many different control information

  1. Max-age specifies the maximum time that the cache expires. This is a relative time compared to the first browser-side request. Private is also used to control that the cache can only be accessed by clients, not proxy servers.
  2. No-store indicates that resources cannot be cached
  3. No-cache indicates that it can be cached but is immediately invalid. A request is sent to the server every time.

The priority of cache-control is greater than that of Expries.

Negotiate the cache

The policy is that the browser sends the request to the server first, and returns the 304 status code if the request content and condition have not changed since the last request, and the newly modified resource if they have changed.

The negotiated cache can also be set up in two ways

last-modify

The first is to return the last modification time of the resource by setting the last-modify attribute in the response header. When the browser sends a request again, the request header will carry the if-modify-since attribute, which is the value of last-modify. The server compares the retrieved header value to the last time the resource was modified, returns the new resource if it is modified, and tells the browser to use the cache if it is not.

However, the drawback of this approach is that last-modify values are only accurate to the second level. If some resources are modified more than once in a second, then the file is modified but last-modify is not changed.

ETag

So the second approach is to set the ETag value in the response header, which holds the unique identifier of the resource and changes when the resource is modified.

When the browser sends a request to the server, it adds an if-none-match header to the request header. The value is the returned ETag value. The server compares the value with the ETag value of the corresponding file to determine whether the value is modified.

ETag takes precedence over last-modify.

Strong cache and negotiated cache both use cached files directly when a cache hit, but negotiated cache requires a request to the server first.

If a strong cache match is made, cache resources are directly used. If no match is made, a request is sent to the server

Negotiation cache is used. If the negotiation cache matches, the browser is informed to use the cache resources. If the negotiation cache does not match, the browser returns the newly modified resources.

57. Ajax for Browser caching?

The problem

Ajax can improve the speed of page loads the main reason is that local refresh, ajax can realize through the local refresh mechanism reduces duplicate data loading, data that is in the load at the same time the data cached in memory, once the data is loaded, as long as no refresh the page, these data will be cached in memory, When the URL we submit is consistent with the historical URL, there is no need to submit to the server, that is, there is no need to fetch data from the server. So, we get the same data that was originally cached in the browser. Although the load on the server is reduced and the user experience is improved, we cannot get the latest data. To ensure that the information we read is up to date, we need to disable its caching function.

The solution

  1. In an ajax request with anyAjaxObj. SetRequestHeader (” the if-modified-since “, “0”).
    1. Principle: if-modified-since :0 deliberately expires the cache
  2. In an ajax request with anyAjaxObj. SetRequestHeader (” cache-control “, “no – Cache”).
    1. Principle: Directly disables the caching mechanism
  3. Add a random number after the URL: “fresh=” + math.random (); .
    1. Principle: Force each request to have a different address
  4. Add time to the URL: “nowtime=” + new Date().gettime (); .
    1. Principle: Force each request to have a different address
  5. $.ajaxsetup ({cache:false}) $.ajaxsetup ({cache:false})
    1. Principle: Ajax caching is not set

58. What is the difference between synchronous and asynchronous?

Synchronization means that code executes sequentially from top to bottom and waits for the current code to return a value or message before continuing to execute the next statement. The program is blocked and cannot continue until the current code returns a value.

Asynchronous means that the code does not wait synchronously for a message to return from the current request to the system before executing down. Instead, it executes subsequent statements directly at the time the code requests, without waiting for the message to return and causing the program to block. An asynchronous program that waits for a message to return before processing it.

59. What is the same origin policy for browsers?

The same origin policy means that if any protocol, domain name, or port number is different, it is non-same origin. Between non-same origin, cookies and localstorage of other websites cannot be obtained through JS, DOM of other websites cannot be operated through JS, and cross-domain request cannot be made through Ajax.

The same origin policy ensures the security of user information, but it does not limit browsers. HTML elements such as IMG and script are not restricted by the same origin policy. (Cross-domain JSONP principle) because these operations do not raise security issues by responding to the results.

60. How to solve cross-domain problems?

  1. The JSONP approach resolves cross-domain requests by defining a callback function in the first place and then dynamically creating a script tag and adding a SRC attribute with a value of non-homologous server side links. The function name and parameter information is received on the server side, processed and finally passed to the browser side js code calling the function. The JS code is defined and the global function call is executed immediately.
  2. CORS cross-domain request. The browser supports this cross-domain request. You only need to set access-Control-allow-origin in the header of the server and set the value to Allow Access to non-source websites of the server.
  3. Websocket protocol, which does not have the same origin policy.

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

Blog.csdn.net/robertzhoux…

62. A quick word about cookies?

What I understand is that cookies are data created by the server to maintain session status information. When the client initiates a request to the server, the server creates cookies and stores the sessionID in cookies and sends it to the client. When the client initiates a request to the server, Cookies are carried by the server to verify whether the user is logged in. Cookies cannot be used for cross-domain requests.

Set-cookies can be used to set cookies on the server side. Expries is used to set the expiration time of cookies. Httponly is used to prevent JAVASCRIPT scripts from obtaining cookies (a defense of CSRF) and can only be accessed by the server. In addition to domain, path, secure.

63. How to do modular development?

Modular development is understood as a set of methods in which different modules implement different functions, and becomes increasingly important as programs become more complex. This reduces maintenance costs and improves efficiency.

64. How many module specifications of JS?

  1. CommonJS: applies mainly to the server side. Exports modules through module.exports to expose module interfaces. Imports modules through require to import modules. CommonJS is executed synchronously because the file methods involved are cached on local disk so there is no obstruction to reading and synchronous execution does not cause code congestion.
    1. ifmodule.exportsIs a basic data type that, like the language itself, is copied and can be reassigned in another module without affecting variable values in other modules.
    2. For complex data types, e.gArray.ObjectA shallow copy refers to a single memory space at the same time, so changes to the value of one module can affect the other.
    3. When usingrequireWhen the command loads the same module, instead of executing the module, it fetches a value from the cache, i.e.,CommonJSNo matter how many times the module is loaded, it will run once on the first load and return the result of the first run when it is loaded later, unless the system cache/module output is manually cleared as an object and the attribute values in the module output are changed
    4. Cyclic loading:CommonJSIt is load-time, when the script code is executedrequireOnce a module is lofted, only the executed part is output (the output here represents only the executed output of the lofted module imported from another module, i.e. variables in exports), and the unexecuted part is not output
  2. AMD: If used in the browser sideCommonJSThe module specification waits until the module is loaded. This causes the browser to be in a state of ‘suspended animation’. Therefore, the browser module can only be asynchronously loaded instead of synchronously loaded.
    1. Asynchronous Module Definition (AMD): Asynchronous module definition
    2. AMDThird party library files need to be introduced when using:RequireJS
    3. Modular development on the browser side
    4. inRequireJSStandardized output of module definition in promotion process
    5. Dependency prefixes are preferred: modules are declared when they are defined and loaded immediately.
    6. For dependent modules,AMDIt’s ahead of schedule, butRequireJSfrom2.0At the beginning, it was also changed to be able to defer execution.
    7. Suitable for asynchronous loading of modules in the browser environment, you can load multiple modules in parallel
    8. Increased development costs, and instead of loading on demand, all dependencies must be loaded in advance.
    9. AMDsupportCMDThe way you write it, you have to introduce itSeaJSThe library files. But it is more recommended to rely on the front.
    10. AMDAPIThe default is one when used multiple times,CMDtheAPIStrict division, advocating a single responsibility. Such asAMDIn,requirePoints in the globalrequireAnd the localrequire, all callrequire.CMDIn, there is no overall picturerequire, but according to the completeness of the module systemseajs.useTo realize the loading of the module system. In CMD, every API is simple and pure.
  3. CMD: Generic module definition. It addresses the same problems as the AMD specification, but in terms of how modules are defined and when modules are loaded, CMD also requires the introduction of additional third-party library files,SeaJS
    1. CMDisSeaJSStandardized output of module definitions during the promotion process
    2. Rely on nearby, only when a module is used will be loaded on demand.
    3. Delay the
    4. CMDtheAPIStrict division, advocating a single responsibility
  4. ES6 module specification: Use import and export to export and import modules.
    1. Values in ES6 modules are dynamic read-only references, that is, exported values of the module cannot be changed while referencing them.
    2. For read-only, that is, it is not allowed to change the value of the imported variable, and the imported variable is read-only, whether it is a basic data type or a complex data type. When a module encounters an import command, it generates a read-only reference. When the script is actually executed, it will be evaluated in the loaded module based on the read-only reference.
    3. For dynamic, when the original value changes, so does the value that the import loads. Both basic and complex data types.
    4. The ES6 module is designed to be as static as possible, so that the module dependencies, as well as the input and output variables, can be determined at compile time
    5. CommonJSandAMDDependencies between modules can only be determined at run time. In Code 1, this is essentially a whole loadfsModule (that is, loadfsAll methods of the module), generate an object export, i.e_fs. And then I’m going to get thatstat,exists,reafFileMethod is used. This type of loading is called “runtime loading” because the object is only available at runtime, making it completely impossible to do “static optimization” at compile time.
    6. ES6Modularity is loaded at compile time. Due to theES6Instead of exporting objects, you export throughexportThe command explicitly specifies the output code, then passesimportCommand input. In code 2, the essence is fromfsThere are three methods that are loaded in a module, and you don’t need to load all of them. This loading is called “compile-time loading” or static loading, which means ES6 can load a module at compile time. It is more efficient than the CommonJS module loading method. Of course, this also makes it impossible to reference the ES6 module itself because it is not an object.

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

  1. For dependent modules, AMD executes early and CMD executes late. Since 2.0, however, RequireJS has also been deferred (handled differently depending on how it is written). CMD advocates as lazy as possible.

  2. AMD advocates the dependency front, CMD advocates the dependency nearby. Look at the code

    1. // AMD 
      define(['./a'.'./b'].function(a, b) {  Dependencies must be written in the beginning
          a.doSomething()
          ...
          b.doSomething()
          ...
      }) 
      
      // CMD
      define(function(require.exports.module) {   
          var a = require('./a')   
          a.doSomething()    
          var b = require('./b')   
          b.doSomething()    
          ... 
      })
      
      Copy the code
  3. AMD API default is a when multiple use, CMD API strictly differentiated, advocating a single responsibility. For example, in AMD, require is divided into global require and local require, both called require. In CMD, there is no global require, but according to the completeness of the module system, seajs.use is provided to realize the loading and starting of the module system. In CMD, every API is simple and pure.

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

Look at 64 points

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

Core principle: The core of requireJS is to introduce loading modules by dynamically creating SRC for script tags

Through the regular matching module and module dependencies, ensure the file loading sequence

The loaded files are cached according to the file path

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

Juejin. Cn/post / 684490…

“ECMAScript6” “ECMAScript6” “ECMAScript6”

The addition of classes in ES6, I think, is intended to complement some of the object-oriented features that are missing in JS. It is a syntactic sugar, based on the idea of prototype inheritance. Adding methods to a class is like adding methods to a constructor’s prototype object. With class we can better block code.

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

Document. write is rewriting the page structure, rewriting the entire page instead of the entire document.

InnerHTML simply replaces the content of an element on the page and overwrites the content of a portion of the element.

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

  1. Create new nodes: createElement(), createTextNode()
  2. Add, remove, replace, insert node: Parent.appendchild (node), parent.removechild (node), parent.replacechild (new, old), parent.insertbefore (new, old)
  3. Find nodes: getElementById, getElementsByName, getElementsByTagName, getElementsByClassName, querySelector, querySelectorAll
  4. Attribute operations: getAttribute, setAttribute, hasAttribute, removeAttribute

72. The difference between innerHTML and outerHTML?

For example, for an HTML like this:

<div> I am text <br/></div>Copy the code

InnerHTML: I am the text

OuterHTML External HTML:

I am a text

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

Call takes this as the first argument to the object, followed by arguments passed into the function. The first argument to apply is the object to which this points, and the second argument is the array of arguments passed to the function.

74. JavaScript class array object definition?

An array of classes has an array’s length attribute and index subscript. An array of classes is similar to an array but cannot use array methods.

Class arrays can have array methods in the following ways:

  1. Call calls the array’s slice method for conversion:

    Array.prototype.slice.call(arrayLike);
    Copy the code
  2. Call the array’s splice method to convert:

    Array.prototype.splice.call(arrayLike, 0);
    Copy the code
  3. Apply calls the function’s concat method to implement the conversion:

    Array.prototype.concat.apply([], arrayLike);
    Copy the code
  4. Convert with array. from:

    Array.from(arrayLike);
    Copy the code

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

  1. Array and string conversions: toString(), join()
  2. Array tail manipulation methods: push(), pop(), push arguments can be multiple
  3. Shift (), unshift()
  4. Reverser () sort()
  5. Concat () returns a concatenated array and does not affect the original array
  6. Array interception method: Slice (start, end) is used to slice a portion of an array without affecting the original array
  7. Array deletion method: splice(start, number) used to delete specified items in an array returns the deleted array, affecting the original array
  8. every() some() forEach() filter() map()
  9. reduce()

76. Array fill method?

The fill method of an array fills all elements of the array from the start index to the end index with a fixed value. Fill accepts three parameters, fixed value, start index, and end index. Where the start and end indexes can be omitted and default to 0 and the length value of this object.

array.fill(value, startIndex, endIndex)
Copy the code

77. […]. The length of the?

The length of the corresponding array

78. Improved scope and variable declarations in JavaScript?

Variable declaration promotion means that the declaration of a variable is promoted to the top of the current scope. , when this is scope of js code before implementation will have a parsing process, create the execution context, the initialization code execution need to use the object, when access to a variable to the current scope of the object, the execution context to find variables in the scope of the first is the current execution context variable object, Includes function parameters, all functions, and declared variables.

79. How to write high-performance Javascript?

  1. Follow strict mode: “Use strict”;
  2. Put js scripts at the bottom of the page to speed up the rendering of the page;
  3. Package JS scripts in groups to reduce requests.
  4. Download the JS script in a non-blocking way.
  5. Try to use local variables to hold global variables;
  6. Minimize the use of closures;
  7. Omit window when using window object property methods;
  8. Minimize object member nesting;
  9. Cache DOM node access;
  10. By avoiding the eval and function() constructors;
  11. Pass setTimeout() and setInterval() functions instead of characters as arguments;
  12. Create objects and arrays using direct quantities whenever possible;
  13. Repaint and reflow are minimized.

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

  1. Tag cleanup: Regular cleanup of tagged variables. First, all global variables are marked, then variables referenced by objects or about to be referenced are marked, and the remaining variables are destroyed by the garbage collection mechanism.
  2. Reference counting: Determines whether a variable has an object reference to it, and clears the variable if no object reference exists.

81. What operations cause memory leaks?

A memory leak is a condition in which the amount of memory in a system is constantly shrinking due to the constant use of variables.

  1. An undeclared local variable generates a global variable that remains in memory and cannot be reclaimed.
  2. Closures: Improper use of closures can result in variables that remain in functions and cannot be freed.
  3. We get a reference to a DOM element, and when the element is deleted, the reference to the element remains, thus occupying memory.
  4. If we set the timer and do not clear it, if the timer loop function always has a reference to the external variable, then the variable will remain in memory.

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?

PopStatus + ajax.

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

this === ‘window’ ? ‘brower’ : ‘node’;

Run in browser if global object is Window otherwise in Node environment

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?

If the body is closed before, it will block the loading of other resources. If placed after the body is closed, it does not affect the loading of elements within the body.

Anything before the body will be parsed into the head, anything after that will be parsed into the body.

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

The click event of the mobile terminal has a delay of 300ms, which is because the mobile terminal has double click amplification function. The delay of 300ms is to wait for whether there is a second click to enlarge the screen. If there is no second click within 300ms, it is considered as a click event. Solution: You can set the no zoom property in the View TAB, you can also set the screen size to the desired size, and you can also use the fastClick library.

Click penetration: because the mobile end of the click event has a 300ms delay, touch after 300ms to respond to the click, which may be delayed to an element at the bottom of the element. Solution: Use only touch, if you use click, there will be a delay for each click.

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?

Front-end routing refers to the page with different functions corresponding to different routes is handed over to the front-end. Before, the server returned different pages through different URLS.

Generally, single-page application is suitable for front-end routing. Most of the page structure is not changed, but only part of the structure is changed.

Advantages of front-end routing: There is no need to request the server, relieving the server pressure, providing good user experience and smooth web pages.

Disadvantages of front-end routing: Single-page applications can’t remember where they scrolled before, nor can they remember where they scrolled while moving forward or backward.

Front-end routing can be implemented in two ways: hash and history.pushState. PushState adds a history to the browser, which can be obtained using history.state. And in history mode, the url of the front end must be the same as the URL passed to the back end.

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..) ?

Juejin. Cn/post / 684490…

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

. The first is a window. The navigator userAgent way to obtain, but this way is not accurate because could be rewritten.

The second is function detection, which is unique to each browser, such as ActiveXObject in IE.

89. What is Polyfill?

Polyfill is used to implement native API code that is not supported by browsers.

90. Use JS to get file extensions?

  1. Interception using index subscriptsstringObject.lastIndexOf(substr)– Searches for the last occurrence of the substr character in a string, or -1 if not found
    1. Stringobject. substr(startIndex [,length]) – Truncates the string. If there is no length parameter, truncates the string to the end
    2. Stringobject. substring(startIndex,[stopIndex]) – Truncate string(startIndex: start subscript stop can default to the subscript to end [characters of this subscript will not be truncated! )
  2. Stringobject.split (sep) – Splits the string into an array with the specified delimiter

91. Introduce js throttling and anti – shake?

If an event is continuously triggered on a page, performance will be adversely affected. For example, if the event is continuously triggered on a page, such as page scrolling or mouse movement, event redundancy will be caused and the load of the page will be burdened.

  1. Ensure that event handlers are called only once in a certain period of time when events are continuously raised. Throttling popular explanation is like our tap water, as soon as the valve is opened, the water pouring down, holding the good traditional virtue of thrift, we have to turn the tap down a little, it is best to be as we will according to a certain rule in a certain time interval drop by drop.

    var throttle = function(func, delay) {
      var prev = Date.now();
      return function() {
        var context = this;
        var args = arguments;
        var now = Date.now();
        if (now - prev >= delay) {
          func.apply(context, args);
          prev = Date.now(); }}}function handle() {
      console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
    
    Copy the code
  2. When an event is continuously triggered and no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the specified time, the delay will start again.

    function debounce(fn, wait) {
        var timeout = null;
        return function() {
            if(timeout ! = =null) 
                    clearTimeout(timeout);
            timeout = setTimeout(fn, wait); }}// handle the function
    function handle() {
        console.log(Math.random()); 
    }
    // Scroll events
    window.addEventListener('scroll', debounce(handle, 1000));
    
    Copy the code

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

== indicates that type conversion can be performed before comparison. === indicates strict comparison. False is returned if the type is different

Object.is() is similar to ===, but handles special cases such that +0 and -0 are no longer relative and NaN is equal to itself.

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

  1. Escape is not in the same category

    In simple terms, escape encodes strings (while the other two are urls) to make them readable on all computers. The encoded result is %XX or %uXXXX. ASCII alphanumeric @*/+ characters will not be encoded, the rest will. Most importantly, forget about this method when you need to encode urls. This method works for strings, not urls.

  2. The most common ones are encodeURI and encodeURIComponent

    Encoding urls is common, so these two methods should be of particular concern in practice.

    They are both encoded urls, the only difference being the range of characters encoded, where

    The encodeURI method does not encode the following characters as ASCII alphanumeric ~! @ # $& * () = : /,; ? + ‘

    The encodeURIComponent method does not encode ASCII alphanumeric ~! * () ‘

    So encodeURIComponent has a larger range of encodeURI encodings than encodeURI.

    For a practical example, encodeURIComponent encodes http:// as HTTP %3A%2F%2F whereas encodeURI does not.

  3. What method should be used on what occasion

    1. If it’s just an encoded string that has nothing to do with the URL, use escape.

    2. If you need to encode the entire URL and then use the URL, use encodeURI.

    3. When you need to encode parameters in URL, encodeURIComponent is the best method.

94. The relationship between Unicode and UTF-8?

Scii, Latin, GBK, Big5, and Unicode are all character sets that use two bytes to represent characters, except ASCII, which has one byte to represent characters.

For uniformity, the International Organization for Standardization, ISO, created Unicode to use two bytes to unify all characters in the world.

The American disagreed because Unicode was two bytes, twice the storage space of his previous SCII, which was one byte. So the ISO came up with a solution to compress Unicode from 2 bytes to 1 byte using UTF-8. After 3 bytes of Chinese conversion (Chinese is special, but after compression, it takes up 3 bytes of memory, which increases the space), utF-8 conversion will eventually generate data ranging from 1 to 6 bytes

So UTF-8 is a compression of Unicode, the encoding.

Unicode codes are strings and exist only in memory

Transmission (network) or storage (hard disk) must be encoded, such as UTF-8 / UTF-16 / UTF-32 / GBK/GB2312(bytes, which are binary data)

95. What is the js event loop?

Juejin. Cn/post / 684490…

96. Js depth copy implementation?

// Shallow copy implementations only copy objects
function shallowCope(object){
    if(! object ||typeofobject ! = ='object') return;
    // Determine whether to create an array or an object based on the type of object
    let newObject = Array.isArray(object) ? [] : {};
    for(let k in object){
        if(object.hasOwnProperty(k)){ newObject[k] = object[k]; }}return newObject;
}
// Deep copy implementation
function deepCope(object){
    if(! object ||typeofobject ! = ='object') return;
    let newObject = Array.isArray(object) ? [] : {};
    for(let k in object){
        if(object.hasOwnProperty(k)){
            newObject[k] = 
                typeof object[k] === 'object'? deepCope(object[k]) : object[k]; }}return newObject;
}
Copy the code

97. Write call, apply, and bind functions by hand

/ / write a call
Function.prototype.myCall = function(context){
    if(typeof this! = ='function') {console.error('type error')};// Get parameters
    let args = [...arguments].slice(1),
        result = null;
    // Check whether context is passed in. If not, set context to Window
    context = context || window;
    // Set the calling function to the method of the object
    context.fn = this; result = context.fn(... args);delete context.fn;
    return result;
}

/ / the apply handwriting
Function.prototype.myApply = function(context){
    if(typeof this! = ='function') {
        console.error('type error');
    }
    let result = null;
    context = context || window;
    context.fn = this;
    if(arguments[1]){ result = context.fn(... arguments[1]);
    } else {
        result = context.fn()
    }
    delete context.fn;
    return result;
}

/ / handwritten bind
Function.prototype.myBind = function(newObject){
    if( typeof this! = ='function') {console.error('type error');
    }
    var args = [...arguments].slice(1);
    var that = this;
    return function(){
       return that.apply(newObject, args.concat([...arguments]))
    }
}

Copy the code

98. Implementation of currization of functions

Function corrification is the call to convert a function that takes multiple arguments into a series of single-argument functions.

Function curry(fn, args){let leng = fn.length; args = args || []; return function(){ let subargs = args.slice(0); for( let i = 0; i < arguments.length; i++){ subargs.push(arguments[i]); } if(subargs. Length >= leng){return fn.apply(this, subargs) } else { return curry.call(this, fn, subargs); } } } function fn(a,b,c){ return a+b+c; } var newCurry = curry(fn, 1); newCurry(2); newCurry(3);Copy the code

99. Why 0.1 + 0.2! = 0.3? How to solve this problem?

In the computer, the operation is converted to binary before calculation, JS is calculated in 64-bit double precision format, only 53 significant digits, the subsequent digits will be truncated, so the error is generated.

So solve 0.1 + 0.2! = 0.3 method, using the native way is

parseFloat((0.1 + 0.2).toFixed(10= = =))0.3 // true
Copy the code

100. Introduction to source, inverse and complement codes

Source code is a fixed-point representation of a binary number in a computer. The first digit is a sign bit and the rest are numeric bits.

The inverse and complement of a positive number are the same as the original code, and the inverse of a negative number is 1 at the beginning, and the numeric bit is the inverse of the original code, and the complement is the inverse plus 1

After the speech

Because the word limit can only be divided into up and down! JS foundation chapter 2

In this must be referred to the reference article – cattle passenger network god