As the front end of the three musketry JavaScript, can be said to be the most important, is the front-end development of the essential foundation, because of JavaScript, to make the static page produced some dynamic effects, how much do you know about JavaScript? This article has compiled some Javascript basics from personal learning in order to fill in the gaps. Without permission, prohibit reprint, continue to update…

1. Tell me about the major browsers and their kernels that you know

2. The data types in JS are divided into several types and what are they

  • Simple data types: number, string, Boolean, NULL, undefined, symbol

  • Complex data types: Object, array, and function

    Note: Simple datatypes have no properties and methods, and the value of simple datatypes is immutable. The value itself is stored in stack memory. Reference data is stored and copied at one address, and changing one will change the other

3. Understanding stack memory and heap memory

  • Stack memory Stack memory stores some relatively simple data and heap memory address, for example

When num is changed, num1 does not change because num is changed

  • Heap memory Heap memory is the storage of some complex data, the data is stored in heap memory, the address of the data is stored in stack memory, for example

Obj and obj1 refer to the same space in the heap. Changing obj and obj1 is actually changing the same data

3. What are typeof returned values

Number, string, Boolean, undefined, object, function

  • Typeof TYPEOF Mandatory string

  • Typeof NULL, Typeof object, and Typeof array all return Object

  • Return false: 0 “” null NaN undefined undefined expression

4. How do I check if an object is an array

  • The first method:instanceofThe Prototype operator tests whether an object has a constructor’s prototype property in its prototype chain.

Analysis process:

The arr.__proto__ attribute points to array. prototype, the prototype object from which the arR constructor is constructed. Constructor === Array arr. Constructor === Array Arr. Constructor === Array arr. Constructor === Array

Note: However, this method has a loophole and may not be accurate because we can change the “this” of an object. We won’t go into too much detail here

  • The second method:Object.prototype.toStringTo borrowObjectMethod on the prototype to implement detection array

Analysis process:

ToString methods are methods on Object prototypes, like function and Array, which override toString methods as instances of Object. From the knowledge of prototype chain, we can know that when we call toString method, we cannot directly call the toString method on Object prototype, but call the rewritten method. Therefore, if we want to get the specific type of the Object, we should use the toString method on the Object prototype borrowed by Call, as explained in the MDN documentation

  • The third method:Array.isArrayThis method takes a parameter that determines whether the value passed is an Array

Analysis process:

This method is a new method in ES5, which can directly determine whether the parameter is an array type, the MDN documentation explains

5. Increment and decrement operators and logical operators

  • ++Operators: written to the end is called postincrement, written to the front is called preincrement
let a = 10
let b = ++a + a++
console.log(a) / / 12
console.log(b) / / 22
// a++ a+ a+ b = 11 + 11 = 22 // a++ A + B = 12

let a = 5
let b = a++ + ++a + a++
console.log(b)  / / 19
console.log(a) / / 8

let a = 10
let b = a-- + ++a
console.log(b) / / 20
console.log(a) / / 10
Copy the code
  • — operator: Same as the increment operator, but not much more

  • Logical operator

    • The whole truth is true only when a false is a false

    • | | : that’s false, before all is false false There is a true is true

    • ! : takes the inverse conversion to a Boolean value

6. Bubble sort

  • The primary version

    • The result of comparing each value in the array in pairs is that the largest number is at the end of the array
    let arr = [23.46.45.39.66.82]
    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            let temp = arr[i]
            arr[i] = arr[i + 1]
            arr[i + 1] = temp
        }
    }
    console.log(arr)
    Arr [0] = arr[0] = arr[0] = arr[0] So length minus 1, I up to 4. When I is 4, arr[4] is compared to arr[5], that is, arr. Length-2 is compared to arr. Length-1
    Copy the code
    • By running the result of the comparison multiple times, the largest number is pushed back one at a time, so a for loop controls how many times the comparison is performed
    for (j = 0; j < arr.length - 1; j++) {
        for (let i = 0; i < arr.length - 1; i++) {
          if (arr[i] > arr[i + 1]) {
                let temp = arr[i]
                  arr[i] = arr[i + 1]
                  arr[i + 1] = temp
          }
          }
    }
    Copy the code
  • Advanced version

    // Run 0 compares 5 times more than 0 times
    // Find the largest number
    // Find the two largest numbers
    // I have already found the largest number in the first circle, so I can do it once less. But the for loop is still going five times, so it's going to be more than one, and so on
    let arr = [23.46.45.39.66.82]
    for (j = 0; j < arr.length - 1; j++) {
        for (let i = 0; i < arr.length - 1 - j; i++) {  // Let length be subtracted by j
            if (arr[i] > arr[i + 1]) {
                let temp = arr[i]
                    arr[i] = arr[i + 1]
                    arr[i + 1] = temp
            }
            }
    }
    Copy the code
  • Final version If in the sorting process, the array is already sorted, the following times do not need to be sorted

    • Hypothesis establishment method
    // Check whether all the grades in the array pass
    let arr = [80.100.90.65.54]
    // First way:
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] >= 60) {
            console.log('I passed them all.')}else {
            console.log('Fail')}}// The second way to think about it is that if you find a score less than 60, not all of them have passed
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < 60) {
            console.log('Not all of them.')}Copy the code

    When sorting, we assume that the array is sorted, so we don’t have to sort it again. In other words, as long as the latter term is greater than the former term, then the hypothesis is not true

    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > arr[i + 1]) {
            console.log('Hypothetical failure')}Copy the code
    • Optimize bubble sorting
    let arr = [23.46.45.39.66.82]
    for (j = 0; j < arr.length - 1; j++) {
        let flag = true
        for (let i = 0; i < arr.length - 1 - j; i++) {
        	if (arr[i] > arr[i + 1]) {
                flag = false
                let temp = arr[i]
            	arr[i] = arr[i + 1]
            	arr[i + 1] = temp
        	} else if (flag == true) {break}}}Copy the code

7. Describe the shallow copy and deep copy

  • Shallow copy: Copies a layer of attributes of an object. If there are other objects in the object, only the address is copied. Modifying one of them will affect each other and is suitable for copying simple data types
let obj = {
    name: 'zs'.age: 18.money: 1000
}
function Copy(obj) {
    let newObj = {}
    for (let k in obj) {
        newObj[k] = obj[k]
    }
    return newObj
}
console.log(Copy(obj))
Copy the code
  • Deep copy: Copies multiple layers of an object, if any, recursively
let obj = {
    name: 'zs'.age: 18.money: 1000.smoke: {
        brand: 'suyan'.num: 20}}function Copy(obj) {
    let newObj = {}
    for (let k in obj) {
        newObj[k] = typeof obj[k] === 'object'? Copy(obj[k]) : obj[k]
    }
    return newObj
}
console.log(Copy(obj))  // Changing obj does not affect newObj
Copy the code

8. Tell me what you understand about prototypes and prototype chains

Functions have the Prototype property, which is an object we call a prototype object; Each object has a __proto__ property, which points to the prototype object, which is also an object and has a __proto__ property, so that layer by layer forms a chain structure, which we call the prototype chain

9. Understanding closures

When the internal function refers to the variable of the external function, it forms a closure. The closure will cause the original scope chain not to be released, resulting in a memory leak. In some places, it is not specific to say that an internal function is stored outside to form a closure. The internal function is stored outside to make it easier to call the internal function, and the reason for nesting functions is that local variables are needed. If it is a global variable, it will not serve the purpose of closure

  • Advantages of closures: form private space, avoid global pollution; Persistent memory, which holds data

  • Disadvantages of closures: memory leaks caused by persistent memory. The solution is to avoid nesting functions. The variable is set to null, allowing the garbage collector to reclaim and free memory

Classic case: Click Li to get the subscript

<ul>
  <li>111</li>
  <li>222</li>
  <li>333</li>
  <li>444</li>
  <li>555</li>
</ul>
  var lis = document.querySelectorAll('li')
  for (var i = 0; i < lis.length; i++) {
    (function (j) {
      lis[j].onclick = function () {
        console.log(j)
      }
    })(i)
  }
Copy the code

10. Differences between call, apply and bind methods

  • Both the call and apply methods can call functions, and the first argument inside the method can be modified to point to this

  • The call method can take multiple arguments, except for the first argument, which identifies this as pointing to. The other arguments are passed to the function as arguments. The apply method takes at most two arguments. The first argument identifies this as pointing to, and the second argument is an array or pseudo-array, each of which is passed to the function as an argument

  • The bind method cannot automatically call a function; it creates a copy of the function, and the this bound to the new function points to the new function returned by Bind

11. What are the pseudo-arrays

  • Function argument list arguments

  • List of DOM objects and list of childNodes childNodes

  • Jquery objects such as $(“div”)

12. What is the difference between a pseudo-array and a real array, and how can a pseudo-array be converted to a real array

The difference between

  • A pseudo-array is actually an object. A real Array is an Array

  • Pseudo-arrays have the length property, but the length cannot be changed. The length of real numbers can be changed

  • Pseudo-arrays do not have the methods of real arrays, such as push, slice, and so on

conversion

  • Call calls an array method

  • The array. from method creates a new, shallow-copy Array instance from an array-like or iterable

  • ES6 new syntax extension operator

One thing to note here is that when you use your own pseudo-array, the extension operator can’t convert a real array. You’ll find that your pseudo-array will fail due to the lack of an Iterator

13. Know about array dimensionality reduction (flattening)

  • Lends a concat method on an array prototype

    let arr = [1.2.3[4.5]]
    Array.prototype.concat.apply([], arr)
    Copy the code
  • Use the concat method and extension operator for arrays

    let arr = [1.2.3[4.5]] [].concat(... arr)Copy the code

Note: the above two methods can only implement one layer of nesting, if it is multiple layers of nesting use the following two methods

  • Use the array. some method to determine whether an Array still exists in the Array. If so, join the Array with the expansion operator and concat

    let arr = [1.2.3[4[5.6]]]
    while (arr.some(item= > Array.isArray(item))) { arr = [].concat(... arr); }console.log(arr);
    Copy the code
  • The flat function in ES6 flattens arrays

    let arr = [1.2.3[4[5.6]]]
    arr.flat( Infinity )
    // The flat infinity property can reduce the dimensions of multiple arrays
    Copy the code

14. var const letWhat are the differences

  • Var contains variable promotion, let const does not

  • Let const has already been declared (has already been declared

  • Let const declarations have block-level scope; var does not

  • A const variable is a constant and cannot be changed, but it can be added to an object or an array

14. This refers to the problem

  • Function call mode, this points to window

  • Constructor call pattern, this points to the newly created instance object

  • Method invocation pattern, this refers to the object calling the method

  • In the context call pattern, the call and apply methods, this refers to the first parameter within the method; In the bind method, the this binding of the new function created by bind is the new function in bind

  • In the event handler,this refers to the current element that triggered the event

  • In timers,this points to the window

  • There is no this in the arrow function to point to the problem; its this is the same as this in the outer scope

  • This in anonymous functions always refers to window

15. How do you understand object orientation and how does it differ from process orientation

  • Object orientation is an idea of software development, which is to regard the program as an object and encapsulate the attributes and methods in order to improve the flexibility, reusability and extensibility of the code. Object orientation has three main features: encapsulation inheritance polymorphism. Encapsulation refers to the ability to store properties or methods in an object, inheritance refers to the ability to derive properties or methods from another class, and polymorphism refers to the ability to write functions or methods that can be run in multiple ways. The advantage of object-oriented development is that it is easy to maintain and expand, reduce the workload and shorten the development cycle, but the disadvantage is that the performance is low

  • Process oriented is a process-centered programming idea, is to solve the problem into a step by step, what to do after doing, and then use functions to implement these steps step by step, when using a call can be. The advantage of procedural is higher performance than object-oriented, because class invocation needs to be instantiated, the cost is relatively large, more consumption of resources; For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor, the disadvantage is not object-oriented as easy to maintain, easy to expand, easy to reuse

16. Array deduplication method

// The first method
const arr = [1.2.3.3.4.5.5.5.7]
const newArr = []
arr.forEach(item= >{
    if(! newArr.includes(item)) { newArr.push(item) } })console.log(newArr)
// The second method es6 adds a new set. The set method has a characteristic that the internal value cannot be repeated
const arr = [1.2.3.3.4.5.5.5.7]
const set = new Set(arr)
const newArr = [...set]  / /... The expand operator can expand arrays or objects
// The third method uses indexof
let arr = [2.8.5.0.5.2.6.7.2]
let newArr = []
for (let i = 0; i < arr.length; i++) {
 if (newArr.indexOf(arr[i]) === -1) {
   newArr.push(arr[i])
 }
}
// the fourth method is sort
let arr = [2.8.5.0.5.2.6.7.2]
arr.sort()
let newArr = [arr[0]]
for (let i = 1; i < arr.length; i++) {
 if(arr[i] ! == newArr[newArr.length -1]) {
   newArr.push(arr[i])
 }
}
Copy the code

Find the intersection of two arrays

const a = [1.2.2.2.3.4.5]
const b = [2.2.3.3]
// The first method:
let arr = a.filter(item= > b.includes(item)) / / whether b inside contain item at this time will take the array a of each out to see if b it is Any return true and filter method as long as it is true remains a array inside there are 3 2 b is 2, so are kept on a 3 2 inside arr =,2,2,3 [2]. But we're looking for an intersection, and we have an extra 2, so this is a poorly thought-out way to find an intersection of arrays

// The second method
let arr = a.filter(item= > {
    const idx = b.indexOf(item)
    if(idx ! = = -1) {
        b.splice(idx,1)
        return true
	} else {
        return false}})Copy the code

18. Find the maximum array size

const arr = [1.2.3.3.5.7.5]
Math.max() // Only values like 1,2,3, and 4 can be accepted as arguments
Math.max.apply(arr,arr) // The first method
Math.max(... arr)// The second method
Copy the code

19. for… In and for… Of the difference between

  • for… In is the key for traversing groups and objects

  • for… Of is the value of the traversal array

20. Scope chains

When a variable is accessed, it looks in the current scope. If it can’t find a variable, it looks in the outer scope. If it can’t find a variable, it returns undefined

21. How to understand the event loop mechanism

Js is a single-threaded language, which may block during execution, so Js is divided into synchronous and asynchronous tasks. Synchronous and asynchronous tasks into different task execution environment, into the main thread synchronization, or main execution stack, asynchronous will throw it to the browser, the browser to read asynchronous code and the asynchronous task, the callback function is added to the task of the queue js after the main thread of task execution, go reading task queue callback, the main thread execution, Js repeats the above process to form an event loop, also known as an event loop

Common asynchronous functions in JavaScript include timers, events, and Ajax

22. Macro tasks and micro tasks

Js divides the task queue into macro task and micro task queue. After each macro task is executed, the micro task queue will be emptied before the next macro task is executed

  • Macro task
    • Entire script tag
    • Asynchronous Ajax requests
    • SetTimeout and setInterval
  • Micro tasks
    • Promise
    • process.nextTick

It is these a few commonly, other temporarily do not know, come a few interview question

console.log(1)

setTimeout(function() {
  console.log(2)},0)

const p = new Promise((resolve, reject) = > {
  resolve(1000)
})
p.then(data= > {
  console.log(data)
})

console.log(3)
// Output 1 3 1000 2
/ * * analysis: Execute 1 synchronously and then encounter timer asynchronous task to the browser, Execute a synchronous promise and mark the promise state as resolve. Then the asynchronous microtask is not executed for the time being. Then perform synchronization 3 and clear the microtask list
Copy the code
console.log(1)
setTimeout(function() {
  console.log(2)
  new Promise(function(resolve) {
    console.log(3)
    resolve()
  }).then(function() {
    console.log(4)})})new Promise(function(resolve) {
  console.log(5)
  resolve()
}).then(function() {
  console.log(6)})setTimeout(function() {
  console.log(7)
  new Promise(function(resolve) {
    console.log(8)
    resolve()
  }).then(function() {
    console.log(9)})})console.log(10)
// Output 1 5 10 6 2 3 4 7 8 9
Copy the code

23. What do you know about Promise

Promise is a JS object that allows asynchronous operations to have the effect of synchronization, eliminating the need for layers of nested callback functions. Each asynchronous task immediately returns a Promise object with three states: Pending Resolved Rejected. The Promise object’s status changes from Successful to Rejected, and the state is irreversible

  • The method on the promise. then prototype functions as a callback function when the state of the Promise instance changes. It takes two callback functions as parameters. The first callback function is called when the Promise object state changes to Resolved, and the second callback function is called when the state changes to Rejected. The second function can be omitted.

  • The method on the promise.catch prototype is used to specify the callback function when an error occurs

  • The method on the promise.finally prototype is supposed to execute the callback no matter what happens to the state of the Promise object, right

  • Promise. Resolve () API itself

    • No parameter returns a new Promise object in the resolve state

    • The pass-through argument is a Promise instance that returns the current Promise instance

  • Promise.reject() returns a value that is passed to the resolve method argument of the next THEN

  • The promise.all () parameter accepts asynchronous operations and can synchronize multiple asynchronous operations and wait for all asynchronous operations to complete before executing a callback

  • Promise.race() Whichever asynchronous result returns the fastest, whether it succeeds or fails

24. The async and await

Async is used to denote that a function is asynchronous, await the result of an asynchronous operation, and async returns a Promise object

Common methods added in ES6-ES10

es6:
1,let,const
2Destruct assignmentlet { a, b } = { a: 1.b: 2 }
3, arrow function4, string template5, extended operator6, array methods: map, filter, etc7, class:classKey Words 8,promise9. Default values of function parametersfn(a = 1) {}
10, short for object propertieslet a = 1; let obj = {a}
11, modular:import-- Introduction, exprotdefaultExport --es7:
1The includes() method, which checks whether an array contains a specified value, and returns if it does, depending on the casetrueOtherwise returnfalse.es8:
1,async/awaitEs9:1,Promise.finally() allows you to specify the final logices10:
1, arrays,ArrayThe flat () and flatmap ()flatThe: method is basically an array dimension reduction methodvar arr1 = [1.2[3.4]];
            arr1.flat(); 
            // [1, 2, 3, 4]

        var arr3 = [1.2[3.4[5.6]]];
        arr3.flat(2);
        // [1, 2, 3, 4, 5, 6]

        // Use Infinity as the depth to expand a nested array of any depth
        arr3.flat(Infinity); 
        // [1, 2, 3, 4, 5, 6]Flatmap: The method first maps (iterates) each element using a mapping function, and then compresses the result into a new arrayCopy the code

26. What are the functions for shaking and throttling, and where did you use shaking and throttling in your project

After the event is triggered, the execution time is recalculated if the event is triggered again. Similar to the mage in the game skill read progress bar and return to the city effect

  • Anti-shake application scenarios:

    • The login button prevents users from clicking and sending requests repeatedly, which can be avoided by using anti-shake

    • If you resize the browser window too often, you can use anti-shake once

    • The text editor saves in real time and saves after one second when there is no change operation

    • To prevent multiple requests from wasting performance, you can use anti-shake processing to send requests after the user stops input for a period of time

  • If you realize

var timerId = null
document.querySelector('.ipt').onkeyup = function () {
    / / image stabilization
    if(timerId ! = =null) {
      clearTimeout(timerId)
    }
    timerId = setTimeout(() = > {
      console.log('I'm anti-shock.')},1000)}Copy the code

Throttling means that no matter how many times the event is triggered in that time period, it will execute the function only once in that time period without recalculating the execution time. Similar to the game in the flat A bar, the speed is fixed, trigger how many times will only attack within a fixed time

  • Throttling application scenarios:

    • Rotation map fixed a period of time to convert an image
  • Throttling implementation

document.querySelector('.ipt').onkeyup = function () {
/ / throttling
    console.log(2)
    if(timerId ! = =null) {
      return
    }

    timerId = setTimeout(() = > {
      console.log('I'm throttling')
      timerId = null
    }, 1000)}Copy the code

27. What does the new operator do

  • A new object is created

  • The constructor is executed and the object is linked to the constructor

  • Changed the constructor’s this to point to the newly created object

  • Return this object

28. Several ways to implement js inheritance

How inheritance is implemented in ES5

  • Borrow constructor inheritance
function Super(name, age) {
  this.name = name
  this.age = 20
}
function Person(name, age) {
  // Change this to Super,
  // So the Person instance will also have all the properties of Super
  Super.call(this, name)
  this.age = age
}
Copy the code

Note: Constructor inheritance cannot inherit property methods on stereotypes

  • Prototype inheritance
function Super(name, age) {
  this.name = name
  this.age = age
  this.leg = 2
}
Super.prototype.say = function () {
  console.log('Hello.'.this.name)
}
function Person(name, age) {
  this.name = name
  this.age = age
}
/** If an instance is used as a prototype object for Person, the Person prototype object will have redundant attributes **/
Person.prototype = new Super()
Person.prototype.constructor = Person
Copy the code

The stereotype inheritance method implements combinatorial inheritance by inheriting properties from constructors

  • Parasitic inheritance
function Super(name, age) {
  this.name = name
  this.age = age
  this.legs = 2
}
Super.prototype.say = function () {
  console.log('Hello.'.this.name)
}
function Person(name, age) {
  this.name = name
  this.age = age
}
// The inherited prototype method is clean, with no redundant attributes
// object. create the new syntax in ES5 can generate a new Object,
// If the argument is passed directly to a constructor, the new object will integrate the properties and methods of the obj object,
Person.prototype = Object.create(Super.prototype) // Only the prototype method is inherited
Person.prototype.constructor = Person
Copy the code

Add constructor inheritance here and you have combinatorial parasitic inheritance

How inheritance is implemented in ES6

  • The class and extends
// Class and extends are syntactic sugars that are essentially inheritance through a chain of stereotypes
class Animal {
  constructor(name) {
    this.name = name
  }
  eat() {
    console.log('Eat it all')}}// Dog
class Dog extends Animal {
  constructor(name, color) {
    super(name)
    this.color = color
  }
  / / barking
  bark() {
    console.log(Woof woof woof)}}const d = new Dog('golden'.'golden')
console.log(d)
Copy the code

A dog inherits name and eat, and has a bark