preface

In order to facilitate the present and future front-end learning and interview, in this collection and arrangement of Js related written interview questions, for their own reference at the same time, I hope it will be helpful to everyone.

Directory:

Front-end HTML+CSS pen test interview question front-end JS pen test interview question front-end small program pen test interview question front-end interview essential dictionary — knowledge in-depth integration

The data type

JS basic data type

Undefined, Null, Boolean, Number, String Add :Symbol

What built-in objects does JS have?

Object is the parent Object of all objects in JavaScript: Object, Array, Boolean, Number, and String Function, Arguments, Math, Date, RegExp, Error

What types can be obtained using Typeof in JS? (考 题 : JS variable type)

typeof undefinded //undefined
typeof null // object
typeof'abc' // string
typeof 123 // number
typeof [] // object
typeof {} // object
typeof true// Boolean typeof b //b is not declared, but undefined is displayedCopy the code

When to use= = =When to use= =? (考 题 : Cast)

Return true if both values and types are equal. Strictly equal 0, NAN, null, undefinded, “”,false is forced to false in if statements

if(obj. A = = null) {/ / here is equivalent to obj. A = = = null | | obj. A = = = undefinded, shorthand / / written here are recommended in the jquery source}Copy the code

Null, and undefinedThe difference between?

1, null: null type, representing “null value”, representing an empty object pointer, using typeof operation to get “object”, so you can think of it as a special object value. 2. Undefined: undefined. When a variable is declared uninitialized, it is undefined.

Ps: In short, null and undefine values are equal, but of different types.

How many ways can Javascript create objects?

1. The way objects are literal

var = {}
Copy the code

2. Create by constructor.

var obj = new Object(); 
Copy the code

3. Create the Object from object.create ().

var obj = Object.create(Object.prototype);
Copy the code

Flipping a string

You can convert the string to an array and then use the reverse()+join() method of the array.

let str="hello word";
let b=[...str].reverse().join(""); //drow ollehCopy the code

describenewThe process of an object

Create a new object. 2. This refers to this. 3

JS distinguishes variable types by storage mode

// Value type var a = 10 var b = a a = 11 console.log(b) var obj1 = {x: 100} var obj2 = obj1 obj1.x = 200 console.log(obj2) // 200Copy the code

How do I determine whether a variable is an object or an array?

The instanceof operator is a property used to test whether an object is in its stereotype chain stereotype constructor

var arr = []; 
arr instanceof Array; // true
Copy the code

The constructor property returns a reference to the array function that created the object, which returns the corresponding constructor

var arr = []; 
arr.constructor == Array; //true
Copy the code

3, the most simple way, it is best to use this kind of writing compatibility Object. The prototype. ToString. Call ()

function isObjArr(value){
     if (Object.prototype.toString.call(value) === "[object Array]") {
            console.log('Value is an array');
       }else if(Object.prototype.toString.call(value)==='[object Object]'){// This method is more compatible with console.log('Value is an object');
      }else{
          console.log('Value is not an array and is not an object')}}Copy the code

4, ES5 add method isArray()

var a = new Array(123);
var b = new Date();
console.log(Array.isArray(a)); //true
console.log(Array.isArray(b)); //false
Copy the code

Ps: Never use typeof for objects and arrays, because both types return “object”.

How to deduplicate an array?

1. De-duplication of Set structure (ES6 usage). ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

[...new Set(array)];
Copy the code

2, traversal, add the value to the new array, use indexOf() to determine whether the value exists, do not add, achieve the effect of de-duplicating.

  let a = ['1'.'2'.'3',1,NaN,NaN,undefined,undefined,null,null, 'a'.'b'.'b'];
    let unique= arr =>{
         let newA=[];
        arr.forEach(key => {
           if(newa.indexof (key)<0){// If there is a key in newA, if there is a key greater than 0, skip the push step newa.push (key); }});returnnewA; } console.log(unique(a)) ; / / /"1"."2"."3", 1, NaN, NaN, undefined, null, "a"."b"] // This method does not distinguish nans; two nans appear. There are problems. The one below is better.Copy the code

3. Use “for” to nest “for” and then splice to de-duplicate it (most commonly used in ES5).

function unique(arr){            
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[I]==arr[j]){// if arr[I]==arr[j]); j--; }}}returnarr; } var arr = [1,1, 1]'true'.'true'.true.true, 15, 15,false.false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a'.'a', {}, {}]; console.log(unique(arr)) //[1,"true", 15, false, undefined, NaN, NaN, "NaN"."a", {... }, {... }] //NaN and {} are not reweightedCopy the code

4. ForEach iterates through and returns an array of the Object’s enumerable properties using object. keys.

    let a = ['1'.'2'.'3', 1,NaN,NaN,undefined,undefined,null,null, 'a'.'b'.'b']; const unique = arr => { var obj = {} arr.forEach(value => { obj[value] = 0; // Add a new attribute and assign the value, otherwise the attribute will not be added})returnObject.keys(obj); } console.log(unique(a)); // 'object.keys (an Object)' returns an array of enumerable properties of the Object. / / /"1"."2"."3"."NaN"."undefined"."null"."a"."b"]
    
Copy the code

Scope and closure

Var, let, constThe difference between

Var is not limited to block level. Var maps to window. Let does not map to window. Var can access variables above the declaration. Const, like let, does not map to window, supports block-level scope, and calls variables above the declaration do not get an error

instructionsThisSeveral different usage scenarios

Execute as constructor; execute as object property; execute as normal function; call apply bind

Talk aboutThisObject understanding

3. In events, this refers to the object that triggered the event. In particular, this in An attachEvent in IE always refers to the global object Window

scope

ES5 scopes are divided into global scopes and functional scopes. ES6 adds block-level scope. Block scope includes {}. {} in if and for statements also belong to block scope.

// block-level scopeif (true) {
    var name = 'zhangsan'} console.log(name) // function and global scope var a = 100function fn () {
    var a = 200
    console.log('fn', a)
}
Copy the code

withJSCreate 10<a>Tag, which pops up when you click on it? (考 题 : scope)

var i 
for (i = 0; i < 10; i++) {
    (function (i) {
        var a = document.createElement('a')
        a.innerHTML = i + '<br>'
        a.addEventListener('click'.function (e) {
            e.preventDefault()
            alert(i)
        })
        document.body.appendChild(a)
    })(i)
}
Copy the code

Explain your understanding of scope chains

1. The function of scope chain is to ensure that the variables and functions that can be accessed in the execution environment are in order. The variables of scope chain can only be accessed up, and the access of variables to the window object is terminated, while the access of variables down by scope chain is not allowed. That is, a scope controls the visibility and lifetime of variables and functions. 3. Generally speaking, a variable takes a value in the scope of the function that created the variable. But if no value is found in the current scope, the chain is called the scope chain

var a = 100
function fnLog (a) console.log(b)} fn() console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(a) console.log(aCopy the code

closure

A closure is a function that can read internal variables of other functions. A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function within a function and access local variables of this function through another function

function F1() {var a = 100 // returns a function as the return valuereturn function() {console.log(a)}} // f1 returns a function var f1 = f1() var a = 200 f1() // 100 defines the parent scopeCopy the code

The characteristics of closures

Nested functions inside functions can refer to arguments and variables that are not collected by the garbage collection mechanism

Tell me what you know about closures

Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have the concept of scope

One of the main uses of closures is to read variables inside functions, and the other is to keep those variables in memory at all times. Disadvantages: memory consumption, improper use will cause memory overflow problem

Considerations for using closures

Because closures cause variables in a function to be stored in memory, which consumes a lot of memory, you should not abuse closures, otherwise it will cause performance problems on the web page, and may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function

Closure usage scenarios

Two scenarios for closures: functions as return values and functions passed as arguments

function F1() {var a = 100 // returns a function as the return valuereturn function() {console.log(a)}} // f1 returns a function var f1 = f1() var a = 200 f1() // 100 defines the parent scopefunction F2 (fn) {
    var a = 200
    fn()
}
F2(f1)
Copy the code

Application of closures in real development

// Closures are used to encapsulate convergent permissionsfunction isFirstLoad() {
    var _list = []
    return function (id) {
        if (_list.indexOf(id) >= 0) {
            return false
        } else {
            _list.push(id)
            return trueVar firstLoad = new isFirstLoad() firstLoad(10true
firstLoad(10) //false
firstLoad(30) //true
Copy the code

Prototype and prototype chain

JavaScript prototype, prototype chain? What are the characteristics?

Every object initializes a property inside of it, called prototype. When we access an object’s property, if the property doesn’t exist inside the object, the object will look for the property in Prototype, which in turn will have its own prototype. And so the search goes on and on, and that’s what we call the prototype chain

Prototype and prototype chain relationships

Relationship: the instance. The constructor. The prototype = instance. __proto__

Prototype and prototype chain characteristics

JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify a Prototype, the object associated with it inherits the change. When we need a property, the Javascript engine looks to see if the property exists in the current object, and if it doesn’t, it looks up whether its Prototype object has the property, and so on, Retrieve the built-in Object PS: 1. All reference types (arrays, objects, functions) have the properties of objects and are free to extend attributes (except for ‘null’) 2. All reference types (arrays, objects, functions) have a _proto_ (implicit prototype) property whose value is a normal object 3. All functions, which have a prototype property, are also a normal object 4. All reference type (array, object, function) _proto_ property values point to the ‘prototype’ property values of his construct

When trying to get a property of an object, if the object itself does not have the property, it will be destroyed_proto_(that is, of its constructorprototype) to look for

// constructorfunction Foo(name, age){
    this.name = name 
}
Foo.prototype.alertName = function() {alert(this.name)} var f = new Foo()'zhangsan')
f.printName = function() {console.log(this.name)} // test f.printName() f.lertName ()Copy the code

Properties of the loop object itself

var item
for (item inF) {// The advanced browser is already infor in// But it is recommended that you add this judgment to ensure the robustness of the applicationif (f.hasOwnProperty(item)) {
        console.log(item)
    }
}
Copy the code

Prototype chain

F.tostring () // Go to f._proto_._proto_Copy the code

Asynchronous and single threaded

What is the difference between synchronous and asynchronous? Give an example of synchronous and asynchronous

Synchronous interaction: The process of sending a request and waiting for it to return before the next request can be sent. Asynchronous interaction: A request can be sent at any time without waiting for a response. The same place: both belong to the interaction mode, both send requests. The difference: one that needs to wait, one that doesn’t. Simply put, synchronization means you have to do one thing at a time and wait until the previous one is done before you can do the next one. Asynchrony is assigning something to someone else and then moving on to the next thing without waiting for someone else to return. Example: 1. Broadcasting is an asynchronous example. The initiator does not care about the status of the receiver. There is no need to wait for a message from the receiver; In some cases, asynchronous interactions that don’t require waiting are preferred in our projects. 2. The telephone is an example of synchronization. The initiator needs to wait for the receiver to answer the phone before the communication starts. Synchronous interactions are used when waiting for the recipient to return information such as the bank’s money transfer system, save operations to the database, and so on. Ps: Alert is synchronous, setTimeout and setInterval are asynchronous. Synchronization blocks code execution, while asynchron does not

How to implement asynchronous programming?

Advantages: simple and easy to understand Disadvantages: not conducive to maintenance, high code coupling

2, event monitoring (using time-driven mode, depending on whether an event occurs) : Advantages: easy to understand, can bind multiple events, each event can specify multiple callback functions Disadvantages: event-driven, process is not clear

Publish/subscribe (observer mode) is similar to event monitoring, but you can know how many publishers and subscribers there are through the ‘message center’

4, Promise object advantages: can use then method, chain writing; Can write error callback function; Cons: Relatively difficult to write and understand

5. Advantages of Generator functions: Data exchange and error handling mechanism inside and outside functions. Disadvantages: inconvenient flow management

6. Advantages of Async function: built-in executor, better semantics, wider applicability, Promise return and clear structure. Cons: Error handling mechanism

Timer execution sequence or mechanism.

In a nutshell: Because JS is single-threaded, when the browser meets setTimeout or setInterval, it will finish executing the current code block first. Before that, it will push the timer into the browser’s waiting event queue. After the browser finishes executing the current code, it will check whether there is any task in the event queue, and then execute the timer code. So even if the timer is set to 0, some of the current code will be executed first.

A aboutsetTimeoutThe pen test

console.log(1)
setTimeout(function () {
    console.log(2)
},0)
console.log(3)
setTimeout(function() {console.log(4)},1000) console.log(5) // Result 1 3 5 2 4Copy the code

The front section uses asynchronous scenarios

2, Network request: Ajax request, dynamic < IMG > loading 3, event binding

Arrays and objectsAPI

What is the difference between map and forEach?

1. ForEach method, the most basic method, is traversal and loop. By default, there are three parameters: ForEach (); / / forEach (); / / forEach (); / / map (); / / forEach ()

JS array and object traversal way, as well as several ways of comparison

Usually we iterate over a set of numbers in a loop. But loops are one of the causes of JS performance problems. ForEach = forEach; forEach = forEach; forEach = forEach; forEach = forEach; forEach = forEach; ForEach cannot use a break or a continue to break the loop, and a return to skip the loop. ForEach can add a second parameter, which is an array. This in the callback refers to this array. It points to window; In the first approach, for-in needs to analyze each array property, which is very performance expensive. Using an array with a known key is very uneconomical. So try not to use for-in, unless you don’t know what properties you’re dealing with, like a JSON object and in method 2, every time you loop, you check the array length. Reading properties (array lengths) is slower than reading local variables, especially if the array is full of DOM elements, because each read scans the page for selector-related elements, which is much slower

Write a generic that iterates through objects and arraysforEachfunction

function forEach(obj, fn) {var key // Check typeif (obj instanceof Array) {
        obj.forEach(function (item, index) {
            fn(index, item)
        })
    } else {
        for (key in obj) {
            fn ( key, obj[key])
        }
    }
}
Copy the code

An array ofAPI

Map: Iterates through arrays of numbers, returning a new array of callback returnsforEach: can'tbreakWe can stop filter by throwing a new Error in a try/catch. Some: returns an itemtrue, the whole istrueEvery: One item is returnedfalse, the whole isfalseJoin: generate string push/pop by specifying the concatenator, change the array, return push/pop item unshift /shift: head push and pop up, change the original array, returning to action items [wrong] sort (fn)/reverse: sorting and inversion, change the original array concat: connection arrays, does not affect the original array, shallow copy slice (start, end) : Return splice(start, number, value...) IndexOf/lastIndexOf(value, fromIndex): fromIndex: fromIndex: fromIndex: fromIndex: fromIndex: fromIndex Find the array item and return the corresponding subscript reduce/reduceRight(fn(Prev, cur), defaultPrev): perform in pairs, prev is the last reduction functionreturnValue, cur is the current value (starting with the second term)Copy the code

objectAPI

var obj = {
    x: 100,
    y: 200,
    z: 300
} 
var key
for (key inObj) {// Notice the hasOwnProperty, as we did in the prototype chainif (obj.hasOwnProperty(key)) {
        console.log(key, obj[key])
    }
}
Copy the code

Date and random number

To obtain2020-06-10Date of format

Date.now() // Get milliseconds var dt = new Date() dt.getTime() // Get milliseconds dt.getMonth() // dt.getMonth() // month (0-11) Dt.getdate () // day (0-31) dt.gethours () // hour (0-23) dt.getminutes () // minute (0-59) dt.getseconds () // second (0-59)Copy the code

Ps: ES6 new padStart(), padEnd() method can be used to return the date in 06 format

Gets a random number in a string format of consistent length

var random = Math.random()
var random = random + '0000000000'
console.log(random)
var random = random.slice(0, 10)
console.log(random)
Copy the code

DOMandBOMoperation

DOMWhat are the basic data structures

DOM is a data structure with a tree structure

DOMCommon usage of operationsAPIWhat are the

Obtain the DOM node and its property and Attribute. 2. Obtain the parent node and the child node

DOMThe node’sAttributeandpropertyWhat is the difference between

Property is just the modification and acquisition of a JS object Attribute is the modification and acquisition of an HTML tag Attribute

DOMNode operation of

Creating a New node

CreateDocumentFragment () // Create a DOM fragment createElement() // Create a specific element createTextNode() // create a text nodeCopy the code

Add, remove, replace, insert

AppendChild () // Add removeChild() // remove replaceChild() // replace insertBefore() // insertCopy the code

To find the

GetElementsByTagName () // By the tag Name getElementsByName() // by the value of the element's Name attribute getElementById() // by the element Id, uniqueCopy the code

How can I detect browser types by detecting navigator.userAgent in a failed browser

var ua = navigator.userAgent
var isChrome = ua.indexOf('Chrome')
console.log(isChrome)
Copy the code

Use the location.href location.protocol location.pathName location.search location.hash in location to retrieve various parameters

Console. log(location.href) console.log(location.host) // domain console.log(location.protocol) console.log(location.pathname) // Path console.log(location.search) // parameter console.log(location.hash) //history
history.back()
history.forward()
Copy the code

Event mechanism

Please explain what event broker is

Event Delegation, also known as Event Delegation. Is a common technique for binding events commonly used in JavaScript. As the name implies, “event broker” refers to delegating the events that need to be bound to the parent element, allowing the parent element to listen for events. Event broker works by bubbling events from DOM elements.

The benefits of using the event broker are:

It saves a lot of memory and reduces event registration, such as brokering all TD click events on the table is great. 3. It makes it possible to add child objects without binding them again

The event model

The W3C defines events as occurring in three phases: capturing, targetin, bubbling

Bubbling event: when you use event bubbling, the child element fires first, and the parent element fires after the captured event: When you use event capturing, the parent element fires first, and the child element fires after the DOM event stream: < Supports two event models: captured event and bubbling event prevention: In W3c, stopPropagation () is used; CancelBubble = true in IE prevents capture: Prevents the default behavior of the event, such as the jump after click – . In W3c, use the preventDefault () method and set window.event. ReturnValue = false in IE

Write a generic event listener function

function bindEvent(elem,type,selector,fn){
    if(fn==null){
        fn = selector;
        selector = null
    }
    elem.addEventListener(type.function(e){
        var target;
        if(selector){
            target = e.target;
            if(target.matches(selector)){
                fn.call(target,e)
            }
        }else{
            fn(e)
        }
    })
}
Copy the code

Describes the event bubbling process

When an event is bound to an element, it first triggers its own binding and then looks up the event layer by layer, which is called event bubbling

var p1 = document.getElementById('p1')
        var body = document.body
        function bindEvent(elem, type, fn) {
            elem.addEventListener(type, fn)
        } 
        bindEvent(p1, 'click'.function (e) {
                e.stopPropagation()
                var target = e.target
                alert("Activate")})bindEvent(body, 'click'.function (e) {
                var target = e.target
                alert("Cancel")})Copy the code

For a page with an infinite drop-down load of images, how do you bind events to each image

You can use proxies to add behavior by binding an event to the parent element and judging by the target attribute of the event

var div1 = document.getElementById('div1')
        var div2 = document.getElementById('div2')
        function bindEvent(elem, type, fn) {
            elem.addEventListener(type, fn)
        } 
        bindEvent(div1, 'click'.function (e) {
                var target = e.target
                alert(target.innerHTML)
            })
        bindEvent(div2, 'click'.function (e) {
                var target = e.target
                alert(target.innerHTML)
        })
Copy the code

AJAX

AjaxThe principle of

Ajax simply puts an intermediate layer (the Ajax engine) between the user and the server, makes an asynchronous request to the server via an XmlHttpRequest object, gets data from the server, and then updates the page by manipulating the DOM with javascript. Asynchronize user actions and server responses. The most critical step is getting the request data from the server. The Ajax process involves only JavaScript, XMLHttpRequest, and DOM. XMLHttpRequest is the core mechanism of Ajax

Write one by handajaxDo not rely on third-party libraries

Var XHR = null; xhr = new XMLHttpRequest() // 2. Connect to server xhr.open('get', url, trueXhr. send(null); // 4. Accept the request xhr.onreadyStatechange =function() {if(xhr.readyState == 4){
            if(xhr.status == 200){
                success(xhr.responseText);
            } else{ // fail fail && fail(xhr.status); }}}Copy the code

Advantages and disadvantages of Ajax

The advantages of ajax

1. Update data without refreshing (maintain communication with the server without refreshing the whole page) 2. Communicate with the server asynchronously (communicate with the server in an asynchronous way without interrupting user operations) 3. 4, interface and application separation (Ajax interface and application separation, namely data and presentation separation)

The disadvantage of ajax

Ajax does not support the browser back button. 2. Security Issues Aajax exposes the details of the server interaction. 3.

When do you encounter cross-domain problems? What are the solutions?

The cross-domain problem is caused by the same origin policy implemented by browsers for security purposes. The same origin policy restricts documents and scripts from different sources. The same origin policy means that the domain name, protocol, and port of two urls must be identical. Script tag JSONP cross domain, Nginx reverse proxy, Node.js middleware proxy cross domain, backend set security domain name in the header information, backend set CORS on the server.

⚠️ Cross-domain precautions

All cross-domain requests must be approved by the information provider. If they are obtained without permission, the browser same-origin policy is vulnerable

XMLandJSONThe difference between?

In terms of data volume, JSON is smaller and faster than XML.

Data interaction JSON and JavaScript interaction is more convenient, easier to parse processing, better data interaction

Data description JSON is less descriptive of data than XML

JSON is much faster than XML in terms of transfer speed

getandpostThe difference between

2. Get is less secure than POST. 3. Get is cached, but POST is not. 6. Get accepts only ASCII characters as parameter data types, and there is no restriction on POST. 7. Get requests will retain historical records, but parameters in POST will not be retained. Post will submit the request again

When to use post?

Post is generally used to modify resources on the server and has no restrictions on the information sent. For example, a cache file cannot be used (updating a file or database on the server), a large amount of data can be sent to the server (POST has no data limit), and a POST is more stable and reliable than GET when sending user input containing unknown characters

TCPWhy does it take three times to establish a connection?

  • To achieve reliable data transmission,TCPBoth sides of a protocol must maintain a serial number that identifies which packets have been received by the other side. The three-way handshake is a necessary step for communication parties to inform each other of the start sequence number and confirm that the other party has received the start sequence number
  • In the case of two handshakes, at most only the initial sequence number of the connection initiator can be confirmed, and the sequence number selected by the other party cannot be confirmed

ES6

ES5The inheritance andES6What’s the difference?

Inheritance in ES5 is implemented through the Prototype or constructor mechanism. ES5 inheritance essentially creates an instance object of a subclass and then adds the Parent class’s methods to this (parent.apply (this)).

ES6 has a completely different inheritance mechanism, essentially creating an instance object of the superclass, this (so you must call the super() method of the superclass first), and then modifying this with the constructor of the subclass.

Concrete: ES6 defines classes through the class keyword, which contains constructors, and extends between classes through the extends keyword. Subclasses must call the super method from the constructor method, otherwise new instances report an error. Because subclasses don’t have their own This object, they inherit this from their parent class and then process it. If you don’t call super, subclasses don’t get this.

The ps: super keyword refers to an instance of the superclass, which is the this object of the superclass. In the subclass constructor, the this keyword can only be used after super is called, otherwise an error is reported

javascriptHow is inheritance implemented?

Prototype mechanism or apply and call methods to implement the simple, it is recommended to use the constructor and prototype hybrid mode

function Parent(){
        this.name = 'wang';
    }
    function Child(){ this.age = 28; } Child.prototype = new Parent(); Var demo = new Child(); alert(demo.age); alert(demo.name); // Get the inherited attribute}Copy the code

Talk to you aboutES6The understanding of the

New template string (simple string interpolation for JavaScript) arrow function for-of (to iterate over data – such as values in an array). Arguments objects can be nicely replaced by undecided arguments and default arguments. ES6 incorporates promise objects into the specification, providing native Promise objects. Added let and const commands to declare variables. Added block-level scope. The let command actually adds block-level scope. There is also the introduction of the module concept

What’s the difference between an arrow function and a normal function?

  • In vivo functionthisObject is the object at which you define it, not the object at which you use it
  • Cannot be used as constructors, that is, not usednewCommand, otherwise an error will be thrown
  • UnusableargumentsObject that does not exist in the function body. You can use it if you wantRestParameters instead of
  • UnusableyieldCommand, so the arrow function cannot be usedGeneratorfunction

ForEach, for in, for ofThe three difference

ForEach is more commonly used to iterate over numbers, such as objects, or json for of array objects. To iterate over objects, loop over keys with object.keys () for in and loop over values

The Set, the MapThe difference between

Application Scenario Set is used for data reorganization, and Map is used for data storage

Set: 1, the member can not duplicate 2, only the key value without the key name, similar to array 3, can be traversed, add, delete,has methods

Map: 1 is essentially a collection of key pairs, similar to set 2, that can be traversed and converted to various data formats

promiseObject usage, handwritten onepromise

Promise is a constructor, and here is a simple example

var promise = new Promise((resolve,reject) => {
    ifResolve (value)}else {
        reject(error)
    }
})
promise.then(function (value) {
    // success
},function (value) {
    // failure
})
Copy the code

Please describePromiseUse scenario, ‘Promise‘The problem it solves and the current solution for asynchronous operations.

Use scenarios for Promise: Ajax requests, callback functions, complex manipulation judgments. Promise was created in ES6 to address asynchronous programming. Asynchronous operation solutions: Promises, generators, timers, and ES7 async

ECMAScript6How to writeclassWhyclassThis stuff?

This syntactic candy makes JAVASCRIPT easier for people with OOP roots, at least an official implementation, but for people familiar with JS, it doesn’t have much impact; An object.creat () handles inheritance and is much cleaner than class

Algorithms and others

Bubble sort

Each time you compare two adjacent numbers, if the latter one is smaller than the previous one, switch places

var arr = [3, 1, 4, 6, 5, 7, 2];

function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
    for(var j = 0; j < arr.length - i - 1; j++) {
        if(arr[j + 1] < arr[j]) { var temp; temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; }}}return arr;
}
console.log(bubbleSort(arr));
Copy the code

Quick sort

Using a dichotomy, take the middle number and compare the array with the middle number each time, putting the small number to the left and the large number to the right

var arr = [3, 1, 4, 6, 5, 7, 2];
function quickSort(arr) {
    if(arr.length == 0) {
        return[]; } var cIndex = math.floor (arr.length / 2); var c = arr.splice(cIndex, 1); var l = []; var r = [];for (var i = 0; i < arr.length; i++) {
        if(arr[i] < c) {
            l.push(arr[i]);
        } else{ r.push(arr[i]); }}return quickSort(l).concat(c, quickSort(r));
}
console.log(quickSort(arr));
Copy the code

Lazy loading

<img id="img1" src="preview.png" data-realsrc = "abc.png"/>
<script type = "text/javascript">
var img1 = document.getElementById("img1")
img1.src = img1.getAttribute('data-realsrc')
</script>
Copy the code

The cacheDOMThe query

// Uncached DOM query var Ifor (i = 0; i < document.getElementByTagName('p').length; I++) {/ / todo} / / cache the DOM querying var pList = document. The getElementByTagName ('p')
var i 
for (i= 0; i < pList.length; i++) {
    // todo
}
Copy the code

mergeDOMinsert

var listNode = document.getElementById('list') / / to insert 10 li tag var frag = document. CreateDocumentFragment (); var x,lifor (x = 0; x < 10; x++) {
    li = document.createElement('li')
    li.innerHTML = "List item" + x
    frag.appendChild(li)
}
listNode.appendChild(frag)
Copy the code

Event throttling

var textarea = document.getElementById('text')
var timeoutId
textarea.addEventListener('keyup'.function () {
    if (timeoutId) {
        clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(function() {// trigger event}, 100)})Copy the code

Operation as soon as possible

window.addEventListener('load'.function() {/ / page finished loading all the resources to perform, including images, video}) document. The addEventListener ('DOMContentLoaded'.function() {//DOM render can be executed, this time the image, video may not complete loading})Copy the code

Shallow copy

The first solution to this problem is object.assign

let a = {
    age: 1
}
let b = Object.assign({}, a)
a.age = 2
console.log(b.age) // 1
Copy the code

Deep copy

Parse (json.stringify (object)) this problem can usually be solved with json.parse (json.stringify (object))

let a = {
    age: 1,
    jobs: {
        first: 'FE'}}let b = JSON.parse(JSON.stringify(a))
a.jobs.first = 'native'
console.log(b.jobs.first) // FE
Copy the code

The array dimension reduction

[1, [2], 3].flatMap(v => v)
// -> [1, 2, 3]
Copy the code

If you want to completely reduce the dimension of a multidimensional array, you can do this

const flattenDeep = (arr) => Array.isArray(arr)
  ? arr.reduce( (a, b) => [...a, ...flattenDeep(b)] , [])
  : [arr]

flattenDeep([1, [[2], [3, [4]], 5]])
Copy the code

preload

In development, you might encounter situations like this. Preloading is a declarative fetch that forces the browser to request the resource and does not block the onload event. You can use the following code to enable preloading

<link rel="preload" href="http://example.com">
Copy the code

Preloading can reduce the loading time of the first screen to some extent, because some important files that do not affect the first screen can be loaded later. The only disadvantage is poor compatibility

pre-rendered

The downloaded files can be pre-rendered in the background by pre-rendering, which can be turned on using the following code

<link rel="prerender" href="http://poetries.com">
Copy the code

Performance optimization

JavaScript Performance Optimization

1, as far as possible to put the <script> tag after the body, to avoid JS execution stuck DOM rendering, to ensure the page as soon as possible to display 2, as far as possible to merge JS code: extract public methods, object-oriented design...... 3, CSS can do things, as far as possible not JS to do, after all, JS parsing execution is rougher, and CSS is more efficient. 4. Manipulate the DOM as much as possible, and pre-order CSs styles to reduce reflow or repaint. 5. Create the DOM as little as possible and use display: None in HTML and CSS to hide and display as needed. 6, compress the file size, reduce the burden of resource download.Copy the code

A few basic JavaScript specifications

1. Do not declare multiple variables on the same line. = = to comparetrue/falseSwitch statements must have a default branch 6. Functions should not sometimes return a value, sometimes not 7. For loops must use curly braces 8.forVariables in the -in loop should be explicitly scoped using the var keyword to avoid scope contaminationCopy the code

How to answer a series of questions that impress an interviewer

  • How does Js self understand scopes and closures