preface

I am small white, inspirational to do technology male god handsome force, currently living in Nanjing, do nearly 3 years of front-end engineer, will continue to write notes.

js

Some common methods for strings

  • Common methods
    • The charAt() method returns the character at the specified position in the string.
    • Split // Splits a String into an array of strings by splitting the String into substrings.
    • Slice // Extracts a portion of the string and returns the new string, retrieving strings with indexes 1, 2, 3, i.e. [1, 4]
    • The substr(start, length) // method returns a substring from the specified position to the specified length
    • Substring (start, end) // Returns a substring between (or to the end of) two indexes of a string.
    • Trim () // Deletes whitespace at both ends of a string
    • ToLowerCase () // converts the string value of the call toLowerCase and returns.
    • ToUpperCase () // converts the string toUpperCase and returns.
  • The regular way
    • Search // Performs a lookup to see if the string object matches a regular expression.
    • Replace // is used to compare regular expressions directly with strings, and then replace the matched substring with a new one.
    • Match // When a string matches a regular expression, the match() method extracts the match.

Some common methods for Array objects

  • Methods that do not change the original array
    • Concat () // Concates two or more arrays
    • Join () // Puts all the elements of the array into a string
    • Slice (start, end) // Returns a new array containing elements from the arrayObject from start to end (excluding the element)
    • ToString () // Converts a logical value to a string and returns the result
  • Change the original array
    • Pop () // Deletes and returns the last element of the array
    • Push () // Wants to add one or more elements to the end of the array
    • Shift () // Removes the first element from the array
    • Unshift () // Adds one or more elements to the beginning of the array
    • Splice () // Adds items to or removes items from the array
    • Reverse () // Used to reverse the order of elements in an array
    • Sort () / / order
  • other
    • ForEach cannot break, so it can be stopped with a try/catch throw new Error
    • Map: Iterates through arrays of numbers, returning a new array of callback returns
    • Filter: filter
    • Some: If one of the entries returns true, the whole is true
    • Every: One of the items returns false, the whole is false
    • IndexOf/lastIndexOf(value, fromIndex): Finds an array entry and returns the corresponding subscript
    • Reduce/reduceRight(fn(Prev, cur), defaultPrev): Execute in pairs, prev is the return value of the last reduction function, cur is the current value (starting from the second item)
  • Array out of order:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.sort(function () {
    return Math.random() - 0.5;
});
Copy the code
  • Flat: [1,[2,3]] –> [1, 2,3]
Array.prototype.flat = function() {
    return this.toString().split(',').map(item => +item )
}
Copy the code

For in for of forEach map

  • The for… in
    • The array is not necessarily iterated in index order.
for(let pro in arr){
    console.log(pro+':' + arr[pro])
}
//0:123
//1:abc
Copy the code
  • The for… of
    • Statement creates an iteration loop over iterable objects (Array, Map, Set, String, TypedArray, Arguments objects, and so on), executing statements for the values of each different attribute.
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let [key,value] of iterable) {
  console.log(key+':'+value);
}
//a:1
//b:2
//c:3
Copy the code
  • forEach
    • The forEach method performs the provided function once forEach element in the array /Map/Set. This function takes three arguments:
      • The current element being processed, in the case of a Map element, represents its value;
      • The index of the current element being processed, in the case of a Map element, represents its key, and in the case of a Set, is the same as the value.
      • The array object that the forEach() method is manipulating.
ForEach (function(value,index,currentArr){currentArr[index]=value + 1}) console.log(arr)//[2, 3, 4, 5]Copy the code
  • map
    • The map() method creates a new array, and the result is the result returned when each element in the array calls one of the provided functions. The function takes three arguments:
      • The current element
      • The current index
      • The array currently being called
var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); // Roots is [1, 2, 3], numbers is still [1, 4, 9]Copy the code

Depth copy

  • Shallow copy: Copies a reference object as an assignment, still pointing to the same address, and changes will affect the original object
    • Object.assign
    • Expansion operator (…)
  • Deep copy: A full copy of a new object, the original object is not affected when modified
    • Json.parse (json.stringify (obj)): Fastest performance
      • An error is reported when an object has a circular reference
      • Cannot be copied when the value is function, undefined, or symbol
    • Recursively, one by one
Function deepClone1(obj) {function deepClone1(obj) { Var objClone = array.isarray (obj)? [] : {}; // Deep copy cannot be empty, If (obj && typeof obj === "object") {for (key in obj) {if (obj. HasOwnProperty (key)) {if (obj[key] && typeof obj[key] === "object") { objClone[key] = deepClone1(obj[key]); } else { objClone[key] = obj[key]; } } } } return objClone; } function deepClone2(obj) {var _obj = json.stringify (obj), objClone = json.parse (_obj); return objClone; }Copy the code

Operator priority

The top priority is the highest:

Var a = {n:1}; var a = {n:1}; var b = a; a.x = a = {n:2}; = = = = = = = = = = = = = = = = = = = = = = = = = = = = = q: console. The log (a.x) = undefined console. The log (b.x) = {2} n:Copy the code

Prototype/constructor/Instance/Prototype chain (Object. The prototype. __proto__ value is null)

All functions have the same implicit prototype attribute (__proto__), pointing to the explicit prototype of Function (function.prototype).

All functions have 2 properties showing the prototype property (prototype) and the implicit prototype property (__proto__)

The implicit prototype property (__proro__) of the object (instance) is the display prototype property (prototype) of its constructor

All functions, whether built-in or custom, are instances of const XXX = new Function()

1. The default Object that the display prototype points to is an empty Object instance Object (but Object points to null) 2. All functions are instances of Function (including Function itself)

  • Prototype: A simple object used to implement object property inheritance. Can be simply understood as the father of the object. In Firefox and Chrome, each JavaScript object contains a __proto__(nonstandard) attribute pointing to its parent (the object’s prototype), accessible from obj.__proto__.

  • Constructor: a function that creates an object using new.

  • Instance: Objects created through constructors and new are instances. Instances point to prototypes via __proto__ and to constructors via constructor.

  • A prototype chain is made up of prototype objects. Each object has a __proto__ attribute that points to the prototype of the constructor that created the object. __proto__ connects the objects together to form the prototype chain. Is a finite chain of objects that implements inheritance and shared properties.

Const instance = new Object(); const instance = new Object(); // Const prototype = object.prototype instance.__proto__ === prototype. constructor === constructor This line is actually obtained based on the prototype, can be understood as a mapping line based on the prototype // for example: // const o = new Object() // o.constructor === Object --> true // o.__proto__ = null; The value of an Object's implicit prototype attribute (__proro__) is the value of its constructor's prototype attribute (prototype)Copy the code

Perform context/variable object/scope/scope chain/variable promotion

This is something I wrote about in my brief introduction to page from URL to page load completion (second note). You can only look at these four points and then you can look at the conclusion in the subtitle which I explained in detail in code.

closure

Closure functions: Functions declared in a function are called closure functions. (Note: the garbage collection mechanism and execution context are involved here, as well as the brief introduction to page from URL to page load completion (second note).)

[[scope]] property: refers to the parent variable object (AO) and the scope chain, i.e. contains the parent variable object (AO) and the variable object (AO).

Closures belong to a special class of scopes called static scopes. Its definition can be understood as: when the parent function is destroyed, the returned child function’s [[scope]] still retains the parent variable object and scope chain, so it can continue to access the parent variable object. Such a function is called a closure.

  • Closures cause a classic problem:

    • The [[scope]] of multiple subfunctions all point to the parent at the same time and are fully shared. So when the parent variable object is modified, all child functions are affected.
  • Solution:

    • Variables can be passed in as function arguments, avoiding the default [[scope]] look-up
    • Use the setTimeout wrap, passed in as the third argument
    • Use block-level scopes to make variables properties of their own context and avoid sharing
  • The characteristics of

    • Make it possible for external access to variables inside functions;
    • Local variables are resident in memory;
    • Can avoid the use of global variables, to prevent global variables pollution;
    • Can cause memory leaks (when a chunk of memory is occupied for a long time and not released)
  • Closure: An inner function can always access parameters and variables declared in its outer function, even after its outer function has been returned (end-of-life).

  • Closure creation:

    • Closure is the ability to create a separate environment, each inside the closure of the environment is independent of each other. Closures can leak memory and create a new address each time the external function executes at a different reference address. However, any data in the current active object that is referred to by the internal subset is not deleted. A pointer is reserved for the internal active object
Function funA(){function funB (){}} <! Function funA(){var a = 10; // The active object of funA; Return function(){// The active object of the anonymous function; alert(a); } } var b = funA(); b(); / / 10 <! -- example --> function outerFn(){var I = 0; function innerFn(){ i++; console.log(i); } return innerFn; } var inner = outerFn(); Inner (); inner(); inner(); inner(); inner(); inner(); var inner2 = outerFn(); inner2(); inner2(); inner2(); // Answer: 1 2 3 1 2 3 <! Var I = 0; function outerFn(){ function innnerFn(){ i++; console.log(i); } return innnerFn; } var inner1 = outerFn(); var inner2 = outerFn(); inner1(); inner2(); inner1(); inner2(); // Answer: 1 2 3 4Copy the code

Script introduction

  • HTML static<script>The introduction of
  • Js dynamic insert<script>
  • <script defer>: lazy loading, executed after element parsing is complete
  • <script async>: loads asynchronously, but blocks element rendering during execution

DOM events

  • Event level:
  1. El.ο nclick=function(){}

It is not allowed to bind multiple events of the same type to the same element/tag (for example, to bind three click events to the BTN element above). DOM0 event binding, binding methods to the element’s event behavior that are executed during the bubbling (or target) phase of the current element’s event behavior.

  1. There are no DOM 1 level events because there is no DOM 1 level event content
  2. DOM 2: El.addeventListener (event-name, callback, useCapture)

Event-name: indicates the event name, which can be a standard DOM event

Callback: A callback function that is injected with an argument to the current event object, event, when an event is triggered

UseCapture: The default is false, indicating that the event handle is executed during the bubble phase

  1. DOM level 3 is written in the same way as DOM level 2 except that more event types are added to the DOM level 2 events

UI events that are triggered when the user interacts with elements on the page, such as Load and Scroll

Focus events, which are triggered when an element gains or loses focus, such as blur and focus

Mouse events, such as dblclick and mouseup, are triggered when the user performs actions on the page using the mouse

A wheel event that is triggered when a mousewheel or similar device is used, such as mousewheel

A text event that is triggered when text is entered into a document, such as textInput

Keyboard events, such as keyDown and keyPress, are triggered when users perform operations on the page using the keyboard

A composite event that is triggered when a character is entered for the IME, such as compositionStart

Change event, triggered when the underlying DOM structure changes, such as DOMsubtreeModified

DOM3 events also allow users to customize some events.

Event bubble/event capture/DOM event flow

  • The event bubbling

IE’s stream of events is called event bubbling, where events are initially received by the most specific element (the node in the document with the deepest nesting level) and then propagated up the hierarchy to the less specific node (the document). All modern browsers support event bubbling and will bubble the event all the way to the Window object.

photo

  • Event capture

The idea of event capture is that less specific nodes should receive events earlier, while the most specific nodes should receive events last. The intent of event capture is to catch an event before it reaches its intended destination. IE9+, Safari, Chrome, Opera, and Firefox support it, and capture starts from Window (although the DOM2 level event specification requires document). Few people use event capture because older browsers don’t support it.

  • DOM event flow:

The event flow is the order in which events are received from the page. Dom2-level events specify that the event flow consists of three phases:

- Event capture stage: The intention is to capture the event before it reaches the target, in the event capture stage event flow model: Document → HTML → Body →div (the stage when the event propagates from the window object to the target node from top to bottom) - in the target stage 2: Actual target-to-event (the stage where the real target node is processing the event) - Event bubble phase: events are received by the most specific element and propagated up to the less specific node. Event flow model: Div → Body → HTML → Document (the phase in which events propagate from the target node to the Window object bottom-up)Copy the code

photo

  • Event delegate (Event broker)

Event delegation is exactly what it sounds like: Delegating an event to another element. You use the DOM’s event bubbling principle to bind the event to the parent node of the target element.

  • Advantages:

    1. Reduced memory consumption and improved performance (no need to bind events for each child element)
    2. Dynamically bound events

If you want to bind events to a large number of element nodes, the perfect solution is to use event delegates, which bind events directly to the parent nodes of these elements and fire events on all child nodes with only one binding.

The bubbling process of events also takes time, and the closer you get to the top, the longer the “event propagation chain” of events, the more time it takes. If the DOM is deeply nested, events bubbling through a large number of ancestor elements can result in a performance penalty. And based on that, we can optimize this for the next point

  • data-*
    • Property is used to store private custom data for a page or application.
    • Can be used for optimization of event delegates

JS runtime mechanism

Why is JS single threaded

As a browser scripting language, JS is mainly used to interact with users and manipulate the DOM. This means that it has to be single-threaded, which can cause complex synchronization problems. (If there are two threads of JavaScript, one thread adds content to a DOM node and the other thread removes it, which thread should the browser use?)

JS Synchronous and asynchronous tasks

One of the hallmarks of the JavaScript language is single-threaded, which means you can only do one thing at a time. If the first task takes a long time, the second task has to wait forever. The designers of the JavaScript language are aware of this problem and divide all tasks into two types, synchronous and asynchronous

  • A synchronization task refers to a task that is queued to be executed on the main thread. The next task can be executed only after the first task is completed.
  • An asynchronous task is one that does not enter the main thread but enters a “task queue” (task queue), an asynchronous task is executed on the main thread only when the “task queue” notifies the main thread that it is ready to execute
Task queue (message queue)

The task queue holds asynchronous tasks that must wait until the execution stack is empty.

For asynchronous tasks, functions are first registered in the event list. If an event in the event list is triggered, the function is moved to the task queue (DOM operations correspond to DOM events, resource loading operations correspond to load events, and timer operations can be considered to correspond to an “out of time” event).

Macro and micro tasks

  • Macro-task: Includes overall code script, setTimeout, setInterval, setImmediate, I/O, UI rendering
  • Micro-task: Promise, Process. nextTick, MutationObserver
  • Significance of microtasks:

Reduce the number of renders during updates

Because according to the HTML standard, the UI is rerendered after the macro task has finished and before the next macro task has started. If the data update is done in MicroTask, you can get the latest UI when macro-Task is finished. If a new Macro-task is created to update the data, the render will be executed twice

Event Loop

  1. When the overall script(as the first macro task) starts executing, all the code is divided into two parts: “synchronous task” and “asynchronous task”;
  2. The synchronization tasks are directly executed in the main thread.
  3. Asynchronous tasks are subdivided into macro tasks and micro tasks;
  4. The macro task enters the Event Table and registers the callback function in the Event Table. Each time the specified Event completes, the Event Table moves this function to the Event Queue.
  5. The microtask also goes to another Event Table and registers a callback function in it. When the specified Event completes, the Event Table moves this function to the Event Queue.
  6. When tasks in the main thread are completed and the main thread is empty, the Event Queue of microtasks will be checked. If there are tasks, they will all be executed. If there are no tasks, the next macro task will be executed.
  7. This process is repeated over and over again. This is the Event Loop;
Summary of one diagram (event loop, execution stack, task queue, macro task, micro task)

Classic Interview questions
console.log(1);

setTimeout(()=>{
    console.log(2);   
    new Promise((resolve,reject)=>{
    console.log(3);
    resolve()
}).then(res=>{
    console.log(4); 
})
})

new Promise((resolve,reject)=>{
    resolve()
}).then(res=>{
    console.log(5); 
}).then(res=>{
    console.log(6);
    
})

new Promise((resolve,reject)=>{
    console.log(7);
    resolve()
}).then(res=>{
    console.log(8); 
}).then(res=>{
    console.log(9);
    
})

setTimeout(()=>{
    console.log(10);   
    new Promise((resolve,reject)=>{
    console.log(11);
    resolve()
}).then(res=>{
    console.log(12); 
})
})

console.log(13);
Copy the code

Results:

The Event object uses

  1. PreventDefault behavior: event.preventdefault ()

What is the default event? For example, the form click submit button to jump to the page, a label default page jump or anchor point positioning, etc. 2. Prevent bubbling: Event.stopPropagation () – The method prevents events from bubbling to the parent element and any parent event handlers from being executed. – stopImmediatePropagation Prevents both events from bubbling to the parent element and other listeners of the element’s event type from being fired

  • Event.currenttarget is always listening for events
  • Event. target is the actual sender of the event

Call () and the apply ()

Change the direction of this, meaning: implement (multiple) inheritance

Can be interpreted as replacing a method of XXX with a method of XXX.

  • Call () : The first argument is that the this value does not change, except that the rest of the arguments are passed directly to the function. When using the call () method, the arguments passed to the function must be enumerated one by one.

  • Apply () : Passes an array of arguments to the function

1. function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add. Call (sub,3,1) // replace sub with add. Call (sub,3,1) == add(3,1); 2. function Animal(name){ this.name = name; this.showName = function(){ alert(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName(); / / Animal. The call object (this) means the use of Animal instead of this object, then the Cat does not have Animal in all of the attributes and methods, the Cat object can be called directly Animal methods and properties.Copy the code

Handwritten EventEmitter(Publish-subscribe model — Easy version)

Emitter class EventEmitter {constructor() {this.events = {}; } // Implement subscription on(type, callBack) {if (! this.events) this.events = Object.create(null); if (! this.events[type]) { this.events[type] = [callBack]; } else { this.events[type].push(callBack); }} // Delete subscription off(type, callBack) {if (! this.events[type]) return; this.events[type] = this.events[type].filter(item => { return item ! == callBack; }); Function fn() {callBack(); function fn() {callBack(); this.off(type, fn); } this.on(type, fn); } // Emit the event emit(type,... rest) { this.events[type] && this.events[type].forEach(fn => fn.apply(this, rest)); }} Const event = new EventEmitter(); const handle = (... rest) => { console.log(rest); }; event.on("click", handle); event.emit("click", 1, 2, 3, 4); event.off("click", handle); event.emit("click", 1, 2); event.once("dbClick", () => { console.log(123456); }); event.emit("dbClick"); event.emit("dbClick");Copy the code

Js data type

This is something I wrote about in my second note on page loading from URL to page loading

The execution of the new operator

  • Create a new object
  • Link to prototype: obj.proto = con.prototype
  • Binding this: apply
  • Returns a new object (or if the constructor has its own retrun)
Function _new(func) {// let obj= {}; // The _proto_ of the empty object refers to the constructor's prototype member object obj.__proto__ = func.prototype; // // let obj= object.create (func.prototype) // Properties and methods are added to the object referenced by this let result = func.apply(obj); If (result && (typeof (result) = = "object" | | typeof (result) = = "function")) {/ / if the results of the constructor returns an object, So return this object return result; } // If the constructor does not return an object, return the new object created. }Copy the code

How to create objects:

Let a={name:' XXX '} // 2 Function Person(name){this.name=name} let b=new Person(' XXX ') // 3.Object. Create (proto, proto) [propertiesObject]) // object.create () let c= object.create ({name:' XXX '})Copy the code

Instanceof principle

Returns true if the prototype object pointed to by the constructor’s Prototype property can be found in the instance’s prototype object chain. That is:

// __proto__: represents the prototype object chain instance.  === instance.constructor.prototype // return trueCopy the code

Reuse of code

When you see any code being written a second time, start thinking about reuse. There are generally the following ways:

  • Function encapsulation
  • inheritance
  • Copy the extend
  • With mixins
  • Use the apply/call

inheritance

In JS, inheritance usually refers to prototype chain inheritance, that is, by specifying the prototype, and can inherit the properties or methods on the prototype through the prototype chain.

  • Optimization: The Holy Grail mode
var inherit = (function(c,p){
	var F = function(){};
	return function(c,p){
		F.prototype = p.prototype;
		c.prototype = new F();
		c.uber = p.prototype;
		c.prototype.constructor = c;
	}
})();
Copy the code
  • Using ES6 syntactic sugar class/extends Using extends indicates which parent class it inherits from, and super must be called in the subclass constructor
class Son extends Father { constructor(name) { super(name); this.name = name || "son"; }}Copy the code

Type judgment

It is not a bug to judge the typeof Target by using typeof alone. The essential reason is JS’s theory that everything is an object. So to really make a good judgment, we need to distinguish between:

  • Basic type (NULL): Use String(null)
  • Basic type (string/number/Boolean/undefined) + function: Use typeof directly
  • Other reference types (Array/Date/RegExp Error): Determine by [object XXX] after calling toString
<! --> let class2Type = {} 'Array Date RegExp Object Error'.split(' ').foreach (e => class2type['[Object '+ e)  + ']' ] = e.toLowerCase()) function type(obj) { if (obj == null) return String(obj) return typeof obj === 'object' ? class2type[ Object.prototype.toString.call(obj) ] || 'object' : typeof obj }Copy the code

modular

Modular development has become an essential part of modern development, which greatly improves the maintainability, extensibility, and collaboration of projects. In general, we use ES6 modular support in the browser and CommonJS modular support in Node.

  • Classification:

    • es6: import / export
    • commonjs: require / module.exports / exports
    • amd: require / defined
  • Distinction between require and import

    • Require supports dynamic import, import is not supported, under proposal (Babel support)
    • Require is a synchronous import, and import is an asynchronous import
    • Require is a value copy. Changes in the exported value do not affect the imported value. Import refers to a memory address, and the imported value changes with the exported value

Anti-shake and throttling

The anti-shake and throttling function is one of the most commonly used high-frequency trigger optimization methods, which can greatly help performance.

  • Debounce: The optimization of multiple high-frequency operations to be performed only on the last time, usually in the case of user input, only one input verification is performed after the input is completed.
function debounce(fn, wait, immediate) { let timer = null return function() { let args = arguments let context = this if (immediate && ! timer) { fn.apply(context, args) } if (timer) clearTimeout(timer) timer = setTimeout(() => { fn.apply(context, args) }, wait) } }Copy the code
  • Throttling: To reduce the frequency and optimize high-frequency operations into low-frequency operations, you need to throttle the operation every 100 to 500 ms. The operation scenario is scrollbar or REsize events.
function throttle(fn, wait, immediate) { let timer = null let callNow = immediate return function() { let context = this, args = arguments if (callNow) { fn.apply(context, args) callNow = false } if (! timer) { timer = setTimeout(() => { fn.apply(context, args) timer = null }, wait) } } }Copy the code

The function executes to change this

Due to the design principle of JS: in functions, you can reference variables in the runtime environment. Therefore, we need a mechanism that allows us to retrieve the current runtime environment from within the function body, and that is this. So to understand what this refers to, we really want to understand the environment in which the function is running, or in human terms, who called the function. Such as:

  • Obj.fn (), which calls the function obj, is this === obj
  • Fn (), here we can call window.fn(), so this === window

However, this mechanism does not fully meet our business needs, so there are three ways to manually change the direction of this:

  • call: fn.call(target, 1, 2)
  • apply: fn.apply(target, [1, 2])
  • The bind: fn. Bind (target) (1, 2)

ES6/ES7

  • The statement

    • Let/const: block-level scope, no variable promotion, temporary dead zone, no duplicate declaration allowed
    • Const: Declares a constant and cannot be modified
  • Deconstruction assignment

    • Class/extend: Class declaration and inheritance
    • Set/Map: New data structure
      • A Map is a structure of key-value pairs with extremely fast lookup times.
      Var names = ['Michael', 'Bob', 'Tracy']; var names = ['Michael', 'Bob', 'Tracy'] var scores = [95, 75, 85]; // Select scores from names and scores from scores. The longer the Array, the longer the score. // If you use Map, you only need a "name" - "score" comparison table, directly according to the name of the search results, no matter how big the table, the search speed will not be slower. Var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]); m.get('Michael'); // initializing a Map requires a two-dimensional array or an empty Map. Map has the following methods: var m = new Map(); // empty Map m.sat ('Adam', 67); // add a new key-value m.set('Bob', 59); m.has('Adam'); // if there is key 'Adam': true m.et ('Adam'); // 67 m.delete('Adam'); // delete key 'Adam' m.net ('Adam'); Var m = new Map(); var m = new Map(); m.set('Adam', 67); m.set('Adam', 88); m.get('Adam'); / / 88Copy the code
      • Set
      // Set is a Set of keys similar to Map, but does not store values. Because the key cannot be repeated, there is no duplicate key in Set. // To create a Set, supply an Array as input, or create an empty Set: var s1 = new Set(); Var s2 = new Set([1, 2, 3]); Var s = new Set([1, 2, 3, 3, '3']); s; // Set {1, 2, 3, "3"} // Note that the number 3 and string '3' are different elements. // Add (key) can be used to add elements to a Set. It can be repeated, but it does not work: s.dd (4); s; // Set {1, 2, 3, 4} s.add(4); s; Set {1, 2, 3, 4} var s = new Set([1, 2, 3]); s; // Set {1, 2, 3} s.delete(3); s; // Set {1, 2}Copy the code
  • Asynchronous solutions:

    • The use and implementation of Promise
    • generator:
      • Yield: pauses the code
      • Next (): Continue executing the code
          function* helloWorld() {
            yield 'hello';
            yield 'world';
            return 'ending';
          }
          const generator = helloWorld();
          
          generator.next()  // { value: 'hello', done: false }
          generator.next()  // { value: 'world', done: false }
          generator.next()  // { value: 'ending', done: true }
          generator.next()  // { value: undefined, done: true }
          
      Copy the code
    • Await/async: syntax sugar for generator, Babel is based on promise implementation.
    async function getUserByAsync(){
       let user = await fetchUser();
       return user;
    }
    
    const user = await getUserByAsync()
    console.log(user)
    Copy the code

Part of the article is collated from

  • What is BFC? This one is enough
  • On JS Prototype
  • Javascriptjs prototype and prototype chain and inheritance related issues
  • Senior front-end factory interview secrets, escort for you jin SAN Silver four, direct factory
  • The front-end high-frequency interview questions The front two years – earning 30 k | the nuggets technical essay
  • Closures, this article is enough to take you through the nature of closures
  • JS deep copy of several implementation methods
  • Event bubbling, Event capture, DOM2 Event flow and Event delegate, Event objects in DOM events
  • JS string Summary of common methods
  • Common methods of Array objects

conclusion

The above is my first note, I am a little blank, if the writing is not good, please correct me, I want to learn deeper knowledge, I hope to make friends with you, I hope my notes to provide you with a comfortable viewing experience.