This is the first day of my participation in the August Challenge. For details, see:August is more challenging
Recently in preparation for autumn recruitment interview, followed a lot of predecessors and big guys public number, also read the nuggets in many big guys front end of the article, very useful to me, I put them down below, so that they can further study.
Draught does not forget to dig the well, thank you again, each big guy’s article I will do a summary one by one in the following
1.JS data types and storage methods
Answer: Js has 7 primitive data types and 1 reference data type
// Raw data type
null
undefined
Boolean
Number
String
Symbol(new) ES6BigInt
// Reference the data type
Object
/* Object contains: normal Object Array regular Object RegExp Date Function Math Function Function */
Copy the code
Storage: Raw data types are stored in stack memory, and reference data types are stored in both stack memory and heap memory (reference type Pointers are stored in stack, and stored Pointers point to the starting address of data in heap memory)
2.JS data type judgment
1. Use typeof judgment
Disadvantages: The original data type is null and the reference data type except Function is Object
typeof 1 //'number'
typeof '1' //'string'
typeof undefined //'undefined'
typeof true //'boolean'
typeof Symbol(a)//'symbol'
typeof [] //'object'
typeof {} //'object'
typeof console.log() //'function'
Copy the code
2. Use instanceof
Disadvantages: Cannot accurately determine the original data type, only the reference data type can be determined
Principle: Instanceof determines whether the prototype of an object can be found in the prototype chain
1 instanceof Number //false
true instanceof Boolean //false
'string' instanceof String //false
[] instanceof Array //true
console.log() instanceof Function //true
{} instanceof Object//true
Copy the code
3. The use of the Object. The prototype. ToString. Judgment call ()
Object.prototype.toString.call(1) //Number
Object.prototype.toString.call(true) //Boolean
Object.prototype.toString.call('string') //String
Object.prototype.toString.call(Symbol()) //Symbol
Object.prototype.toString.call(null) //null
Object.prototype.toString.call(undefined) //undefined
Object.prototype.toString.call([]) //Array
Object.prototype.toString.call({}) //Object
Object.prototype.toString.call(console.log()) //Function
Copy the code
3. Difference between null and undefined
Both null and undefined are basic data types in Javascript. Undefined means that the variable should have a value but is not defined, and NULL means that it should not.
4. The difference between == and ===
=== is a strict operator, and == is an equality operator
1. Strict operator comparison rules
- Compare different types: different types return directly
false
- Same type (raw data type) : Return if the values are equal
true
, do not want to wait to returnfalse
- Same type (reference data type) : refers to the same object
true
Otherwise returnfalse
2. Equality operator comparison rules
-
Raw type comparison: All data are converted to numeric types and compared
-
Object to primitive type comparison: The object is compared after being converted to a value of the primitive data type
-
Implicit conversions exist in the equality operator
What is worth mentioning is the comparison between null and undefined.
null= = =undefined //false
null= =undefined //true
Copy the code
5. The prototype chain
Here’s an article that’s easy to understand: “You Need to Understand Prototypes and Prototype Chains, whether you’re interviewing or not” by Nick Chen. Here’s a picture of Nick Chen’s above article and a classic prototype chain picture. An object’s __proto__ refers to its prototype. prototype, up to null. Its prototype. constructor refers to its prototype. prototype
6. Js inheritance
ECMAScript only supports implementation inheritance and relies heavily on prototype chains. The inheritance of Js includes prototype chain inheritance, borrowing constructor inheritance, combination inheritance, original type inheritance, parasitic inheritance, parasitic combination inheritance six. This article writes about two types of inheritance: composite inheritance and parasitic composite inheritance
Composite inheritance (prototype chain inheritance + constructor inheritance)
// Define the constructor
function Parent(age){
this.age = age
}
// Set the Parent method
Parent.prototype.sayAge = function(){
console.log(this.age)
}
// Define the Child and use the constructor to inherit the age property of Parent
function Child(age){
Parent.call(this,age)
}
// Inherit Parent's sayAge method through the prototype chain
Child.prototype = new Parent()// The constructor is called once
// Create the Child instance
const childInstance = new Child(18)
console.log(childInstance.age)/ / 18
console.log(childInstance instanceof Parent)//true
Copy the code
- Advantages: Parent methods are reusable, constructors are passable, inherited attributes are not shared
- Disadvantages: Unnecessary properties in the superclass, wasted memory, two constructor calls
Parasitic combination inheritance
- Parasitic combination inheritance optimizes combination inheritance, makes up for the shortcoming of calling the constructor of the parent class when inheriting the parent class, and avoids unnecessary attributes
- Principle: In inheritance, there is no inheritance of the parent class
Instance objects
So that there is no call to the parent classThe constructor
, but inheritedThe instance object of the prototype of the parent object
To avoid unnecessary attributes generated during inheritance - Method: Modifying the prototype
// Define the constructor
function Parent(age){
this.age = age
}
// Set the Parent method
Parent.prototype.sayAge = function(){
console.log(this.age)
}
// Define the Child and use the constructor to inherit the age property of Parent
function Child(age){
Parent.call(this,age)
}
// Modify the prototype chain
const prototype = object(Parent.prototype)
prototype.constructor = Child
Child.prototype = prototype
// Create the Child instance
const childInstance = new Child(18)
console.log(childInstance.age)/ / 18
console.log(childInstance instanceof Parent)//true
Copy the code
7. Event dissemination
When an event occurs on a DOM element, it doesn’t just happen on that element. Instead, it starts with window and works its way up to the specified element. Event propagation has the following three stages:
- Capture phase: Event from
window
The trigger starts at a level that escalates inward until it reaches the specified element - Target phase: The event has reached the target element
- Bubble phase: Events bubble from the target element to the outer layer, layer by layer until
window
8. The useCapture parameter of addEventListener
The third optional argument to the addEventListener method is useCapture, which defaults to false. When false, the listener event is emitted during the event bubble phase, and when true, the listener event is emitted during the capture phase
9. Event capture
When an event occurs on a DOM element, it doesn’t just happen on that element. Instead, it starts with window and works its way up to the specified element. Event capture phase, events are: window→document→ HTML →body→ specified element
10. Event delegation
Event delegation essentially takes advantage of the event bubbling mechanism. Events in the process of bubble, uploaded to the parent node, the parent node at the same time can also through the event object positioning to the target child nodes, so the child nodes monitor events can be defined in the parent node, so that you can by a parent to monitor all child nodes under the parent node of events without the need for each child node binding to monitor events, also known as event agent. Event agents reduce memory consumption and enable dynamic binding of events.
11. New ES6 features
- Block scope
- class
- Template string
- Object to deconstruct
- Arrow function
- The module
- Enhanced literal objects
- Default function arguments
- Promise
- Symbol
- set
- proxy
- rest
12. Arrow function features
- There is no definition context of its own
this
Always pointing to the outer layerthis
Not inside the arrow function- Cannot be used as a constructor (cannot be used
new
) - There is no
arguments
13.Set, WeakSet, Map, WeakMap
1.Set
Features:
Element order | Elemental repetition | Storable type |
---|---|---|
A disorderly | Do not repeat | Raw data type + reference data type |
Set Set
let set = new Set(a)/ / create the Set
set.add(0)
set.add(1)
set.add(2) // Add the element
set.delete(2) // Delete the element
set.forEach(item= >{
console.log(item) / / 1, 2
}) / / traverse
set.has(1) // Check whether the collection contains an element,true
set.clear() // Clear the collection
Copy the code
In addition, the reference objects in the Set object have been strongly typed, and can not automatically reclaim useless reference objects, which will cause memory waste, and the cost of recycling is high, WeakSet solves this problem
2.WeakSet
Features:
Element order | Elemental repetition | Storable type |
---|---|---|
A disorderly | Do not repeat | Reference data type |
WeakSet
Only reference objects can be stored, otherwise they will be thrownTypeError
errorWeakSet
Cannot contain objects without references (null
), otherwise the object will beAutomatically reclaim (move out of the collection)
WeakSet
Objects stored inAn enumeration
That is, it cannot be obtainedWeakSet
theThe size of the
And one of theThe element
Related code:
let weakset = new WeakSet(a)let foo = {}
weakset.add(a)
console.log(... weakset)//Exception is thrown
console.log(weakset.size) //undefined
weakset.clear() // There is no such method
// A method to remove an object and check whether elements in the object exist
console.log(weakset.has(a)) //true
foo = null // Automatically reclaim objects without references
console.log(weakset.has(a)) //false
Copy the code
3.Map
Features:
A Map is similar to an object in that it is a collection of key-value pairs, but unlike a traditional object, only values of type Number, String, or Symbol can be used as key names. A Map can be used as key names of any type
Advantages of using Map:
- The same size of memory,
Map
More storage - through
size
To obtainMap
The length of the
Related methods:
/ / base
let map = new Map()
map.set("tony".21)
map.set("steve".22) // Add key-value pairs
console.log(map.get("tony")) // Find value by key, 21
console.log(map.has("tony")) // Check whether the key contains an element, true
console.log(map.delete("steve")) // Delete elements by key, true
console.log(map.has("steve")) //false
// Iterate over the method
let m = new Map([["tony".21],
["steve".22]])for(let key of m.keys()){
//keys() gets the iterator for all keys in the Map
console.log(key)
// "tony"
// "steve"
}
for(let value of m.values()){
//values() Gets a traverser for all values in the Map
console.log(value)
/ / 21
/ / 22
}
//entries() Get all Map key-value pairs iterator
for(let item of m.entries()){
// Normal writing
console.log(item)
// ["tony",21]
// ["steve",22]
}
for(let [key,value] of m.entries()){
// Deconstruction
console.log(key,value)
// "tony" 21
// "steve" 22
}
Copy the code
4.WeakMap
Features:
The characteristics of WeakMap
- Only receive objects as
key
(null
Except) key
Is the weak reference referred tovalue
Can be recycled after recyclingkey
It’s invalid. Members can disappear at any time- Does not support
Map
Gets the traverser in the
14.Proxy
Concept: Proxy can be understood as a layer of “interception” set up before the target object. All external access to the object must pass through this layer, so it provides a mechanism to filter and rewrite external access.
15. This point
Here’s an image from Jake’s blog post, from the basics to the Basics: 66 JavaScript Interview Tips
The picture is very detailed and clear:
- At the global scope,
this
Point to thewindow
- In a function, this always refers to the object that last called the function
- In the constructor, this refers to the instance that was created by new
- In call, Apply, and bind, this refers to the object to be bound
- This in the arrow function always points to this in the parent scope
16. How is new implemented
New = new = new = new = new = new = new = new = new = new = new = new
After new is used, the following steps are performed:
- Create an empty object
Object
({}
) - Link the empty object to another object (required
new
Object) (link to the constructor) - Treat the newly created empty object as
this
context - return
Here’s a snippet of code from Jake’s blog post: From the basics to the Basics: 66 JavaScript Interview Tips
function Dog(name, color, age) {
this.name = name;
this.color = color;
this.age = age;
}
Dog.prototype={
getName: function() {
return this.name
}
}
var dog = new Dog('rhubarb'.'yellow'.3)
Copy the code
Part of the analysis code is as follows:
// Step 1: Create a simple empty object
var obj = {}
// Step 2: link the object to another object (prototype chain)
obj.__proto__ = Dog.prototype
// Step 3: Use the new object created in Step 1 as the context for 'this'. This refers to the obj object
Dog.apply(obj, ['rhubarb'.'yellow'.3])
// Step 4: Return this if the function returns no object
// Because Dog() does not return a value, obj is returned
var dog = obj
dog.getName() // 'rhubarb'
// Return the value of return if Dog() has a return
var rtnObj = {}
function Dog(name, color, age) {
// ...
// Return an object
return rtnObj
}
var dog = new Dog('rhubarb'.'yellow'.3)
console.log(dog === rtnObj) // true
Copy the code
17. Scope and scope chains
- Scope: The area in which variables are defined. It has a set of rules for accessing variables that govern how the browser engine looks for variables in the current or nested scope
- Scope chain: ensures orderly access to the browser engine within the scope. In simple terms, variables that cannot be found in the inner scope are searched out, like a chain
- Scope: nature is actually a pointer to the variable list, the variable object contains all the variables and functions in the execution environment, that is to say, the pointer list is contained in every context, from the inside out of the variable object, global scope of the variable object is the pointer to the last in the list of objects
When looking for a variable, if it is not found in the current execution environment, it is looked back down the scope chain
Var, let, const
var
There are variables that are risinglet
andconst
There is nolet
andconst
The declaration forms a block scope. No variable can be found outside the scope- In the same scope
var
The ability to repeatedly declare variables whilelet
andconst
Can’t const
The assignment must be made at declaration time, if the assignment isBasic data type
, cannot be modified. Otherwise, an error will be reportedReference data type
(object
), cannot be modifiedconst
Object, but properties in the object can be modified
19. Temporary dead zone
In a block scope, if a variable is declared as let and const, it will only be found in the scope of the block, even if the same variable exists outside the scope of the block. Therefore, we have the following code:
var a = 100;
if(1){
a = 10;
// If a is declared let/const in the current scope, if a is assigned 10, then only a is found in the current scope.
// Error:a is not defined
let a = 1;
}
Copy the code
20. Closure
In a nutshell: a closure is a function that has permission to read variables inside the scope of another function
Common use:
- Creating a private variable
- Store the context variables at the end of the run in memory
Example code:
// Common usage
function a(){
var b = 0;
function c(){
console.log(b)
}
return c
}
const testc = a()
testc()
// Private variables
function person(name,age){
var name = name
this.age = age
this.getName = function(){
return name
}
}
const tony = new person('tony'.21)
console.log(tony.name) //undefined
console.log(tony.age) / / 21
console.log(tony.getName())//tony
Copy the code
You can think of closures as being generated when a function declaration is created. You can think of the game character as having a backpack that contains the lexical scope of all variables in the execution context of the function. For more details, see Medium’s fifty thousand Praise essay – “I’ll Never Understand THE JS Closure” by Nuggets Anthony.
21.JS running mechanism
Javascript is single-threaded, depending on its purpose. Javacript’s main purpose is to interact with users and manipulate the DOM, so it can only be single-threaded. For example, if Javascript has two threads, one that does DOM add and the other that does DOM delete, there will be a contradiction.
22. Macro and micro tasks
- Macro task:
The whole script
,setTimeout
,setInterval
,setImmediate
- Micro tasks:
Promise
,process.nextTick
,MutationObserver
23. Event loop
Let’s start with a personal understanding of the event cycle: In this macro task, if synchronous task is found, it will be executed immediately. If asynchronous task is found, it will be mounted (macro task is mounted to the Event Queue of macro task and microtask is mounted to the Event Queue of microtask). After completing these steps (completion of the macro task), it is considered that one round of Event loop has been performed. After this round of Event loop, it enters the Event Queue to check whether there is any mounted microtask. If there is, it will be executed. Looking for macro tasks in the Event Queue continues the work of executing code, mounting macro tasks, microtasks, and so on.
Continue: macro task → microtask mounted by the previous macro task → macro task mounted by the previous macro task → loop
Personal opinion, learning may not be very deep, if there are mistakes, very grateful for your corrections
Here’s some code:
/* Output: 1.script start 2.script end 3.promise1 4.promise2 5.setTimeout */
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});
console.log('script end');
Copy the code
24.Promise
- Three states:
pending
,fulfilled
,rejected
- Features: Status once from
pending
Change to other states, is immutable - Role: Solve
The callback hell
Problems in a way,Synchronous operation
wayAsynchronous operations
- Disadvantages: Cannot cancel, cannot get progress
This is very depressing. This is very depressing. This is very depressing, which is very depressing. My leader said I have to work overtime because of a new project, so I can’t ask you any more. According to this state, we have a new plan and plan to meet again next week, which is in the state of Rejected.
My understanding: In the last story, this Promise is a Promise. My Promise makes the Promise enter the pending state. When I fulfill the Promise, I will pay for dinner and work overtime, which makes the Promise enter different states respectively. Once the state becomes fulfilled or rejected, the Promise will be resolved and cannot be changed. With resolve, we have a new plan, which is equivalent to using the callback function to get the result and act accordingly
This will be fulfilled: Promise→pending→fulfilled or rejected→ return the callback function which will be fulfilled or rejected→ proceed to the next operation
25. Promise. All with Promise. Race
Promise.all
- Application: Merge requests
- Parameters:
Promise
Object composedAn array of
- Feature: Pass in arrays, multiple
Promise
If all the commands are executed successfully, the system returns successThe callback function
If any of them fails to be executed, the operation fails - Function: Perform multiple asynchronous operations in parallel
The callback function
All results are processed in - Understand: Complete all incoming
Promise
, all successfully returnedSuccessful callback function
, returns if any failure occursFailed callback function
- To execute slowly
Promise
Lord, the last onePromise
After it’s overThe callback
let Promise1 = new Promise(function(resolve, reject){})
let Promise2 = new Promise(function(resolve, reject){})
let Promise3 = new Promise(function(resolve, reject){})
let p = Promise.all([Promise1, Promise2, Promise3])
p.then(funciton(){
// Success is when all three succeed
}, function(){
// If there is a failure, it will fail
})
Copy the code
Promise.race
- Application: Request timeout processing
- Parameters:
Promise
Object composedAn array of
- Feature: Pass in arrays, multiple
Promise
If one of themPromise
Change the state first, thenPromise.race
Returns thePromise
theThe callback function
- Function: Resolves timeout issues
- To execute fast
Promise
Main, returns thePrmise
The operation of theThe callback
const p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() = > reject(new Error('request timeout')), 5000)})]); p .then(console.log)
.catch(console.error);
Copy the code
Race Performs the two asynchronous operations in the parameters. After 5 seconds, the timer triggers the asynchronous operations. P returns the reject callback function, indicating that the request times out
26. Async and await
- Advantages: More readability, more concise code
- Feature: if a function is preceded by
async
, returns onePromise
If, in theasync
Inside the function, let’s writereturn
, the function returns directlyPromise.resolve()
- Note:
await
Only in theasync
Function
The following code is posted, using Promise and async/await, respectively
// The initial code
function takeLongTime(n) {
return new Promise(resolve= > {
setTimeout(() = > resolve(n + 200), n);
});
}
function step1(n) {
console.log(`step1 with ${n}`);
return takeLongTime(n);
}
function step2(n) {
console.log(`step2 with ${n}`);
return takeLongTime(n);
}
function step3(n) {
console.log(`step3 with ${n}`);
return takeLongTime(n);
}
/ / Promise
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
function doIt() {
console.time("doIt");
const time1 = 300;
step1(time1)
.then(time2= > step2(time2))
.then(time3= > step3(time3))
.then(result= > {
console.log(`result is ${result}`);
});
}
doIt();
/ / async/await
async function doIt() {
console.time("doIt");
const time1 = 300;
const time2 = await step1(time1);
const time3 = await step2(time2);
const result = await step3(time3);
console.log(`result is ${result}`);
}
doIt();
Copy the code
27. Async and defer in script tag
Common use:
<script src='xxx'></script>
<script src='xxx' async></script>
<script src='xxx' defer></script>
Copy the code
- Async:
An asynchronous request
Script, if requested, pauseHTML
To perform the parsing of the obtainedJavascript
Code before continuing parsingHTML
- Defer:
An asynchronous request
Script, if the request is received, wait firstHTML
When parsing is complete, execute the obtainedJavascript
code
Disadvantages of async: The timing of obtaining the script is uncertain. When obtaining the script, some DOM elements have not been parsed and may not be obtained by the script. And if there are more than one async, then the script is not controllable
For more details, see the async and defer properties in the Graphical Script tag
28. JS precompiled
Order: global precompile → function body precompile
- Function body precompile
- To create a
AO
Object (activation object
) - Looking for
parameter
As well asVariable declarations
That will beparameter
As well asVariable declarations
As newAO
The object’sattribute
- will
parameter
withThe arguments
unified - Looking for
Function declaration
That will beThe function name
As aAO
The object’sattribute
theattribute
The value ofThe body of the function
- Functions are executed line by line (if a line of code exists
Variable ascension
Ignoring it,The assignment
Don’t ignore)
Step summary: create empty AO object → add variable declaration, parameter to AO object → parameter, argument unity → add function declaration to AO object → execute function line by line
function fn(a) {
console.log(a); //function a() {}
var a = 123; / / assignment
console.log(a); / / 123
function a() {} // The variable has been promoted, ignore
console.log(a); / / 123
var b = function() {}
console.log(b); //function() {}
function d() {}
var d = a / / assignment
console.log(d); / / 123
}
fn(1)
AO:{a:undefined b:undefined d:undefined} 3. {a:undefined b:undefined D :undefined} 3. AO:{a:1 b:undefined D :undefined} 4. AO:{a:function(){} b:function(){} d:function(){}} 5 Using AO objects, step by step according to the code inside the function (the variable promotion part is ignored, but the assignment part is not ignored) */
Copy the code
- Global precompile
- create
GO
Object (global object
) - Looking for a
Variable declarations
, declare the variable asGO
Object attribute name, value assigned toundefined
- Looking for a
In the global
theFunction declaration
That will beThe function name
As aGO
The object’sThe property name
.The body of the function
As theattribute
thevalue
Step summary: create empty GO object → add variable declaration GO object → add function declaration to GO object → execute function line by line (global before function body)
1:global = 100 // Assignment, not declaration
2:function fn() {
3: console.log(global); // undefined
4: global = 200
5: console.log(global); / / 200
6: var global = 300
7:}
8:fn()
GO:{} 2; GO:{} 3 GO:{} 3 GO:{} 3 GO:{fn:function fn() {console.log(global); // undefined global = 200 console.log(global); // 200 var global = 300}} Create an empty AO object AO:{} 2. Find the variable declaration and parameter, write AO{global:undefined} 3. AO{global:undefined} 4 (AO{global:undefined}); (AO{global:undefined}); (AO{global:undefined}); In the first line, the global variable is assigned, and there is no global in the GO object, so a global variable is declared with a value of 100 and 2 is written to the GO object. 3. In line 3, global is undefined in the AO object, so undefined 4 is output. In line 4, global is set to 200 5. In line 5, global is set to 200 6. In line 6, assign global to 300 (steps 3, 4, 5, and 6 are all handled in AO objects) */
Copy the code
29. Differences between AMD, CMD, Module and CommonJs
Differences between AMD and CMD:
AMD
To promoteDependencies are front-loaded and executed ahead of time, i.e.,define
The dependent modules passed in the method are downloaded and executed at the outset (declared when the module dependencies are defined)CMD
To promoteRely on proximity, delay executionIn which therequire
Depends on the module (on demand)- common
AMD
Specification: RequireJs - common
CMD
Specification: SeaJs
Here is a piece of code from JakeZhang
// CMD
define(function(require.exports.module) {
var a = require("./a");
a.doSomething();
// Omit 100 lines here
var b = require("./b"); Dependencies can be written nearby
b.doSomething();
// ...
});
// AMD's default recommendation
define(["./a"."./b"].function(a, b) {
Dependencies must be written from the start
a.doSomething();
// Omit 100 lines here
b.doSomething();
// ...
});
Copy the code
CommonJs and ES6Module:
Relation to dependence:
CommonJs
The establishment of modules and dependencies occurs during the code run (dynamic)Module
Module and dependency creation occurs during code compilation (static)
Nature and Characteristics:
CommonJs
The output is a copy of the value (the output is no longer affected), whereas in ES6Module
The output is a reference to a value (that is, a binding to a variable)CommonJs
Only a single module can be exported, whileModule
Can export multiple
Operating mechanism:
- In the ES6
Module
withCommonJs
When the Js engine performs static analysis on the script, if there isimport
, generates oneRead-only reference
When the script is actually executedRead-only reference
Load the module and get the value (import
I can only write at the top, andCommonJs
Unlimited) CommonJs
Mechanism isRuntime loading
.CommonJs
A module is an object, that is, after a module is loaded, an object is generated, and then methods are read from that objectRuntime loading
30.Js garbage collection mechanism
Js garbage collection two strategies:
- Mark recycling
- Reference counting
Mark recycling
- Tag collection is the most common garbage collection mechanism in browsers. When the variable goes in
The execution environment
, the variable is marked asInto the environment
And left thePerform link
Is marked asLeave the environment
Is marked asLeave the environment
The variable is freed from memory - Garbage collector (
GC
All variables stored in memory are marked at runtime. Then, it will remove the rightThe execution environment
After that, the marked variables will be collected. The garbage collector completes the memory cleaning work, destroying the marked variables and reclaiming the memory occupied by them
Reference counting
- A reference count is a record of each value
The number of times it was referenced
, when a variable is declared and aReference type value
When assigned to the variable, the valuecitations
add1
. Conversely, if the variableIs assigned to another value
, then the valuecitations
Reduction of1
When the valuecitations
for0
, indicating that the value is alreadyNo use value
, the value of this value at the time of collectionmemory
It will beThe release of
- Existing problems: May causeA circular reference. For example, in the following code,
obj1
withobj2
By referring to each other through attributes, when the execution is complete,obj1
,obj2
leftscope
, butobj1
,obj2
The number of references is not0
Is not automatically reclaimed, resulting inA circular reference(the function is incremented by 1 each time it is run), and memory needs to be reclaimed manually.
// For each call, the number of references is incremented by one, never zero
function fun() {
let obj1 = {};
let obj2 = {};
obj1.a = obj2; // Obj1 references obj2
obj2.a = obj1; // Obj2 references obj1
}
// Manually reclaim memory
obj1.a = null
obj2.a = null
Copy the code
Ways to reduce garbage collection
When the code is more complex, the cost of garbage collection will be relatively large, so garbage collection should be minimized as follows:
- right
An array of
Optimize: Set the array manuallyThe length of the
0 - right
object
Optimize:object
Reuse as much as possible, if no longer in use, assign tonull
To make it recycled as soon as possible - right
function
To optimize: if the circulation inside the bodyfunction
Reusable, as far as possible in the circulation outside the body
31. Memory leak
Cause of memory leak:
- Unexpected global variable: A global variable is accidentally created by using an undeclared variable
- Forgotten timer (forgot to cancel
setInterval
) or the callback function (which has a reference to an external variable) cannot be reclaimed - References outside the DOM: Get one
DOM
The element is deleted, but the reference to the element remains, which makes it impossible to reclaim - Unreasonable closures
32.IIFE(call function expression immediately)
Usage: The function is executed immediately after it is created
(function IIFE(){
console.log( "Hello!"); }) ();// "Hello!"
Copy the code
33. for.. In and for… The difference of
Iterating over objects:
for... of
Get the object key,for... in
Gets the object key name
Iterating over an array:
for... of
Get the array elements,for... in
Get array index
The difference between:
for... in
Loops are primarily for traversalobject
, does not apply to traversalAn array of
;for... of
Loops can be used to iterateAn array of
,Arraylike object
.string
,Set
,Map
As well asGenerator
Object.
34. XSS and CSRF
Cross Site Scripting (XSS), also known as cross-site Scripting, is a code injection attack
- Principle: An attacker inserts malicious script code into a page. The user who uses the page runs the script. The attacker uses the script to obtain the user’s code
Cookie
And other sensitive information, jeopardize data security - Categories: stored (persistent, malicious code in the database), reflected (non-persistent, malicious code in the URL), DOM
XSS prevention:
- HttpOnly:
Cookie
Set in thehttpOnly
Properties,Javascript
Script cannot be obtainedCookie
information - Input filtering: Check the input format to avoid
Javascript
Input and upload related script code - The necessary escape of the input and output results
Cross-site Request forgery (CSRF), also known as cross-site request forgery
Here is a picture from the front interview: (7) XSS attack and CSRF Attack — shotCat
- How it works: An attacker uses a dangerous website to use the victim’s
Cookie
To make it look like a dangerous operation by a user - Type: GET, POST, and link
The following code is posted from the same source:
/ / GET type CSRF
<img src="http://bank.example/withdraw? amount=10000&for=hacker" >
/ / after the victim to visit the page containing the img, the browser will automatically ` on to http://bank.example/withdraw? Account =xiaoming&amount=10000&for=hacker ' Bank.example will receive a cross-domain request containing the victim's login information.
/ / POST type CSRF
<form action="http://bank.example/withdraw" method=POST>
<input type="hidden" name="account" value="xiaoming" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
<script> document.forms[0].submit(); </script>
// After visiting the page, the form is automatically submitted, which is equivalent to a simulated user completing a POST. POST type attacks are usually a little more demanding than GET, but still not complicated. Any personal website, blog, and the website uploaded by hackers may be the source of the attack. The back-end interface cannot rely on the security of only allowing POST.
// Link type CSRF
<a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">Blockbuster news!!<a/>// The user clicks to trigger the requestCopy the code
Features:
- Attacks are usually launched on third-party websites
- Attackers use the login credentials of users to impersonate users, rather than directly steal data
- During the whole process, the attacker cannot obtain the user
Cookie
Data, just a fraud - Attacks are usually cross-domain
Precautions against CSRF:
- Use verification codes: prevent requests from being executed directly
- Referer check: The request is not executed if the request source does not meet the requirements
- Use token token: Verify that the token is correct on request
Differences between XSS and CSRF
- XSS is to inject code to implement attacks, CSRF is to exploit users
Cookie
Illegal request Api to implement illegal operation - XSS attacks do not require user login, while CSRF attacks require user login
35. Add, delete, modify and check DOM nodes
/ / to find
document.getElementById(id)
document.getElementByName(name)
document.getElementByClassName(className)
document.getElementByTagName(tagName)
/ / create
document.createElement("h1")
document.createTextNode(String)// Create a text node
document.createAttribute("class")// Create an attribute node
/ / delete
element.removeChild(node)
Copy the code
How do I delete a DOM
Look at the code, source: CSDN
<body>
<div id="main">
<div id="box">111</div>
<div class="box2">222</div>
</div>
<script type="text/javascript">
var box = document.getElementById("box");
var main = document.getElementById("main");
var newMask = document.createElement("div");
newMask.id ="newMask";
main.appendChild(newMask);
if(box){
box.parentNode.removeChild(box); / / in this
}
else{
alert("There is no div.");
}
</script>
</body>
Copy the code
37. ForEach, map, find and filter
forEach
There is no substantial return, generally is the direct operation of the original array, andmap
withfilter
Will allocate memory space to store the new array and return it, without affecting the original array,find
Returns a callback function that does not affect the arrayforEach
Usage: Often used for display (only for traversing groups, no return value)map
Usage: letAn array of
According to onefunction
An array ofEach element
forThe corresponding operation
andRebuild the array
andreturn
(Must have a return value)filter
Usage: letAn array of
According to oneThe rules
For each of the arraysThe element
forscreening
andRebuild the array
andreturn
Callback (arg1, arg2, arg3)
- Arg1: Iterates over the resulting elements
- Arg2: The element index obtained by traversal
- Arg3: The array to iterate over
This code is from JavaScript Arrays (forEach, Map, Filter, Find) — itclanCoder:
//forEach
var obj = {
"data": {"members": [{"id":111."name":"Gao"},
{"id":222."name":"Xiao"},
{"id":333."name":"Wang"}}}]var newArrs= [];
obj.data.members.forEach(function(member,index,originArrs){
newArrs.push(member.name);
})
console.log(newArrs); //[" Xiao Gao ", "Xiao Fan "," Xiao Wang "]
//map
var numbersA = [1.2.3.4.5.6];
var numbersB = []
var numbersC = numbersA.map(function(numberA,index,originArrs){
return numbersB.push(numberA*2);
}
console.log(numbersA); / / [6]
console.log(numbersB);// [2, 4, 6, 8, 10, 12]
console.log(numbersC);// [1, 2, 3, 4, 5, 6]
console.log(numbersC==numbersA) // false
//filter
var persons = [
{name:"Wang".type:"boy".city:"Guangxi".age:15.height:170},
{name:"Little beauty".type:"girl".city:"Beijing".age:16.height:180},
{name:"Gao".type:"girl".city:"Hunan".age:18.height:175},
{name:"Liu".type:"boy".city:"Hebei".age:20.height:177}]var filterPersons = persons.filter(function(person,index,arrs){
return person.type === "boy";
})
console.log(filterPersons) // Filters the entire object of type boy and stuffs it into a new array
Copy the code
References (some mentioned above, in no particular order)
- “2021” high frequency front end test questions summary of JavaScript (part 1) “– CUGGZ
- “2021” high frequency front end test questions summary of JavaScript (part ii) “– CUGGZ
- Don’t rush me to code slowly
- “From the simple to the deep, 66 JavaScript interview knowledge points” by JakeZhang
- # 26 Selected JavaScript Interview Questions — Fundebug
- Further additions may follow
Finally:
Concept article I temporarily write here, these topics are I in this period of time to collect the current part of the company in advance batch, autumn recruitment of some front-end Js interview questions, in the future if encountered did not write the topic, I will continue to update here, if you find that I wrote a mistake, please be corrected, very grateful! Finally, I posted this period of reference to the article sources, thank you very much in the process of sorting out the big guys for my help, I also very harvest, thank you for reading O (^▽^)o, mutual encouragement.
– (finished)