当前位置:网站首页>Red Treasure Book Reading Notes (continuously updated)
Red Treasure Book Reading Notes (continuously updated)
2022-06-13 04:43:00 【Dax1_】
It's today 2021 year 8 month 15 Japan , Start reading front-end related books while self-study , Willing to make progress in learning .
This one is 《JavaScript Advanced programming 》( The Fourth Edition ), Also known as the Red Treasure book , In the Fourth Edition ES6.
The next goal is 《JavaScript Dom Programming art 》( The second edition ), It's already on the side .
Next book ? May be 《 You don't know JavaScript》( Scroll up ), It could be 《 The illustration HTTP》, It's a little helpful for the interview .
Open punch !
The first 1 Chapter , What is? JavaScript
1995 year ,JavaScript available
JS The father of :Brendan Eich
complete JavaScript The implementation consists of the following parts
- The core (ECMAScript)
- Document object model (DOM)
- Browser object model (BOM)
DOM It's a API, Abstract the entire page as a set of hierarchical nodes , Every part of the page is a node , Contains different data . adopt DOM You can easily delete 、 add to 、 Replace 、 Modify node .
BOM, You can manipulate the browser to display parts outside the page .
※ Summary
- EMCAScript: from ECMA-262 Define and provide core functions
- Document object model (DOM): Provides methods and interfaces to interact with web content
- Browser object model (BOM): Provides methods and interfaces to interact with browsers
The first 2 Chapter ,HTML Medium JavaScript
script The elements are as follows 8 Attributes
- async: Optional , asynchronous
- charset: Optional , Use src The code character set specified by the
- crossorigin: Optional , Configure related requests CORS( Cross-domain resource sharing ) Set up
- defer: Optional , It means that it is feasible to execute the script after the document parsing and display are completed , Only valid for external script files
- integrity: Optional , Can be used to ensure CDN Will not provide just content
- language: abandoned
- src: Optional , Represents an external file containing the code to be executed
- type: Optional , Instead of language, Represents the content type of a scripting language
The page resolves to <body> Start rendering at the beginning of the tag
The browser is parsing to the end </html> Tags will execute
Postpone script execution
- defer attribute
- Tell the browser that it should start downloading now , But implementation should be postponed
- Execute in the order in which they appear
- Only valid for external script files
Executing scripts asynchronously
- async attribute
- Tell the browser to start downloading now , But implementation should be postponed
- There is no guarantee that they will be executed in the order in which they appear
- Only valid for external script files
In line code and external files
External files are recommended , For the following reasons :
- Maintainability :JS If the code is spread over a lot HTML page , It can cause maintenance difficulties .
- cache : The browser will cache all external links according to specific settings JS file , This means that if two pages use the same file , Then the file only needs to be downloaded once , Ultimately it means that the page loads faster .
- Adapt to the future : hold JS Put the code in an external file , You don't have to think about using XHTML Or other annotation black technology .
doctype Document mode
- Hybrid mode
- The standard model
- Quasi standard model
※ Summary
- Include the external JS file , Must be src Property to the... That contains the file URL, Files can be on the same server as web pages , Or in a completely different domain
- Usually put <script> Elements at the end of the page , After the main content and </body> Before the label
- defer and async Similarities and differences
The first 3 Chapter , Language foundation
var、let and const
I summarized an article before , It's more detailed : In depth understanding of var、let and const
Statement style and best practices
- Don't use var
- const first ,let second
const Declaration allows the browser to force variables to remain unchanged at runtime , You can also let the static code analysis tool find illegal assignment operations in advance .
data type ( Six simple data types and one complex data type )
- number
- boolean
- string
- symbol(ES6 newly added )
- null
- undefined
- object
undefined == true //true
Never explicitly set a variable value to undefined. but null No , anytime , As long as the variable holds the object , At that time, there was no object to save , To use null Fill in
Numerical transformation
- number()
- parseInt()
- parseFloat()
Convert to string
- toString
toString() The method can be seen in numerical 、 Boolean value 、 Object and string value ,null and undefined No value toString() Method .
Use the plus operator to add an empty string to a value "" You can also convert it to a string
String interpolation :`${}`
Exponential operators
- Math.pow() Have your own operators **
The first 4 Chapter , Variable 、 Scope and memory
ECMAScript Variables can contain two different types of data
- Original value : Is the simplest data
- Reference value : An object composed of multiple values
When you assign a value to a variable ,JS The engine must determine whether the value is original or referenced . The variable that holds the original value is By value (value) Access to the , Because what we operate is Actual values stored in variables .
Reference values are objects held in memory .JS It is not allowed to directly manipulate the memory address of the object . When manipulating objects , In fact, the operation is on the object quote (reference) Rather than the actual object itself . So , The variable that holds the reference value is By reference (by reference) Access to the .
Dynamic properties
- For reference values , You can add... At any time 、 Modify and delete its properties and methods .
- The original value cannot have attributes , Although trying to add properties to the original value does not report an error .
Copy value
- When assigning an original value to another variable through a variable , The original value is copied to the location of the new variable .
- When assigning a reference value from one variable to another , The value stored in the variable is also copied to the location of the new variable . The difference lies in , The value copied here is actually a The pointer , It points to objects stored in heap memory . as follows :
let obj1 =new Object();
let obj2 =new Object();
obj1.name = "frank"
console.log(obj2.name) //"frank"
Pass parameters : The arguments to all functions are By value Delivered .
function setName(obj){
obj.name="frank"
obj = new Oject()
obj.name="Greg"
}
let person = new Object()
setName(person)
console.log(person.name) //"frank"
If person It's passed by reference , that person The pointer should be automatically changed to point to name by “Greg” The object of . But when we visit again person.name when , His value is “frank”, This means that when the value of the parameter in the function changes , The original reference is still the same . When obj When overridden inside a function , It becomes a pointer to a local object , The local object is destroyed at the end of the function execution .
Determine the type
typeof The operator is suitable for determining whether a variable is of primitive type ( If the value is Object or null,typeof return object)
typeof Although useful for raw values , But it is not very useful for reference values .ECMAScript Provides instanceof The operator
grammar :result = variable instanceof constructor
If the variable is an instance of a given reference type , be instanceof Operator return true
console.log(person instanceof Object) // Variable person yes Object Do you ?
console.log(colors instanceof Array) // Variable colors yes Array Do you ?
By definition , All reference values are Object Example , So detect any reference values and Object The constructor returns true, If the original value is monitored , Will return false, Because the original value is not an object .
Execution context and scope
The global context is often said window object , So all of them passed var Defined global variables and functions will become window Properties and methods of objects . Use let and const The top-level declaration of is not defined in the global context , But in scope chain resolution, the effect is the same . The context is destroyed after all of its code has been executed , Including all the variables and functions defined on it ( The global context is destroyed before the application exits , For example, close the web page or exit the browser .)
When code in context is executed , Will create a variable object Scope chain (scope chain). This scope chain determines the order in which the code at all levels of context accesses variables and functions .
summary : The internal context can access everything in the external context through the scope chain , But the external context can't access anything in the internal context .
Scope chain enhancement
- try/catch Of the statement catch block
- with sentence
- In both cases , Will add a variable object at the front end of the scope chain .
- Yes with The statement is , The specified object is added to the front end of the scope chain
- Yes catch Statement , A new variable object is created , This variable object will contain the declaration of the error object to be thrown .
Garbage collection
Realize memory allocation and idle resource recovery through automatic memory management
The basic idea : Determine which variables will no longer be used , Then release the memory it occupies . The process is cyclical , That is, the garbage collection program will run automatically every certain time .
- JS The most common garbage collection strategy is Mark cleaning
- Another less common garbage collection strategy is Reference count
memory management
- adopt const and let Claims to improve performance
- Hide classes and delete operations
- Memory leak ( Unexpected declaration of global variables 、 Timer 、 Closure, etc )
- Static allocation and object pooling
This part of the knowledge about garbage collection is a little abrupt , Later on ” Garbage collection 、 Memory “ This content , Just sum up an article
※ Summary
JS Variables can be saved as two types of values : Raw and reference values .
- The original value size is fixed , So it's stored in stack memory
- Copying the original value from one variable to another creates a second copy of that value
- Reference values are objects , Stored in heap memory
- Variables that contain reference values actually contain only a pointer to the response object , Not the object itself
- Copying reference values from one variable to another only copies pointers , So the result is that both variables point to the same object
- typeof You can determine the original type of the value , and instanceof The reference type used to ensure the value
Any variable exists in a context
- Execution context is divided into global context 、 Function context and block level context
- Every time the code execution flow enters a new context , Will create a scope chain , For searching variables and functions
- The local context of a function or block can not only access variables in its own scope , You can also access variables in any containing context or even in the global context
- Global context can only access variables and functions in global context , You cannot directly access any data in the local context
- The execution context of the variable is used to determine when memory is released
JS It's a programming language that uses garbage collection , Developers don't have to worry about memory allocation and recycling
- Values that leave the scope are automatically marked as recyclable , Then it's deleted during garbage collection
- The mainstream garbage collection algorithm is tag cleaning , That is, mark the currently inapplicable value first , Come back and reclaim their memory .
- Reference counting is another garbage collection strategy , Need to record how many times the value has been referenced .JS The engine no longer uses such an algorithm , But some of the older versions IE Will still be affected by this algorithm
- Reference counting is a problem when there are circular references in the code
- Dereferencing variables not only eliminates circular references , And it's also helpful for garbage collection . To facilitate memory recycling , Global object 、 Properties and circular references of global objects should be dereferenced when they are not needed .
The first 5 Chapter , Basic reference types
Reference value ( Or object ) It's a particular Reference type Example .
Objects are considered to be of a particular reference type example . The new object passes through new
The operator is followed by a Constructors To create . Constructors are functions used to create new objects , For example, downlink
let now = new Date()
This line of code creates the reference type Date A new example of , And save it in the variable now
in .Date()
Here is the constructor , It's responsible for creating a simple object with only default properties and methods .
Date
To create a date object , Just use new
Operator to call Date
Constructors
let now = new Date()
Two auxiliary methods Date.parse()
and Date.UTC()
**Date.parse()
** Method receives a string parameter representing the date , Try to convert this string to the number of milliseconds representing the date .
For example, to create a representation “2019 year 5 month 23 Japan ” Date object for , You can use the following code
let someDate = new Date("May 23, 2019")
If to Date.parse()
The string of does not represent the date , Then the method returns NaN. If you pass the string representing the date directly to Date Constructors , that Date Will be called in the background Date.parse().
let me put it another way , The following line of code is equivalent to the previous line .
let someDate = new Date("May 23, 2019")
These two lines of code result in the same date object .
**Date.UTC()
** Method also returns the millisecond representation of the date , But it's the same as Date.parse()
Different information to generate this value .
Pass to Date.UTC()
The parameter is year 、 Months from zero 、 Japan (131)、 when (023)、 branch 、 Seconds and milliseconds . Of these parameters , Only the first two ( Year and month ) It's necessary . If you don't provide a day , Then the default is 1 Japan . The default values of other parameters are 0.
// GMT Time 2000 year 1 month 1 Japan 0 spot
let y2k = new Date(Date.UTC(2000,0))
// GMT Time 2005 year 5 month 5 On the afternoon of Sunday 5 spot 55 branch 55 second
let allFives = new Date(Date.UTC(2005,4,5,17,55,55))
ECMAScript It also provides Date.now()
Method , Returns the number of milliseconds representing the date and time when the method was executed .
Date Type of valueOf()
Method does not repudiate the string , When this method is rewritten, it returns the millisecond representation of the date .
Primitive value wrapper type
ECMAScript Provides 3 A special type of reference :Boolean
、Number
and String
Whenever you use a method or property with an original value , The background will create an object of the corresponding original packing type , So as to expose various methods of original values .
let s1 = "some text"
let s2 = s1.substring(2)
here , The original value itself is not an object , So logically there should be no way , In fact, this example did work as expected . Because background processing is performed in the background , It is equivalent to doing the following 3 Step by step
- Create a String Instance of type
- Call specific methods on instances
- Destroy instance
You can put this 3 Step imagine executing the following code
let s1 = new String("some text")
let s2 = s1.substring(2)
s1 = null
This behavior allows the original value to have the behavior of the object , Yes Boolean and Number The packaging type is also valid .
** The main difference between a reference type and a primitive value wrapper type is the life cycle of the object .** Re pass new After instantiating the reference type , The resulting instance will be merged when it leaves the scope , The automatically created primitive value wrapper object exists only during the execution of the line of code that accesses it . This means that you cannot add properties and methods to the original value at run time .
let s1 = "some text"
s1.color = "red"
console.log(s1.color) //undefined
The reason for this is that the second line of code will temporarily create a String object , And when the third line of code executes , This object has been destroyed . actually , The third line of code creates its own String object , But this object does not color attribute .
Boolean
Boolean Instance of will override valueOf()
Method , Returns a raw value true or false.toString()
Methods are also overridden when called , Return string “true” or “false”
Number
Number The type also overrides valueOf()
、toLocalString()
and toString()
Method .valueOf()
Method returns Number Object represents the original value , Two other methods return numeric strings .toString()
Method optionally receives a parameter representing the cardinality , And returns a numeric value in the form of the corresponding cardinality character string
let num = 10
console,log(num.toString()) //"10"
console,log(num.toString(2)) //"1010"
console,log(num.toString(8)) //"12"
console,log(num.toString(10)) //"10"
console,log(num.toString(16)) //"a"
toFixed()
Method returns a numeric string containing the specified number of decimal places . If the number of decimal places of the value itself exceeds the number of digits specified by the parameter , Then round to the nearest decimal place
let num = 10.005
console.log(num.toFixed(2)) //"10.01"
toExponential()
Returns a numeric string in scientific notation . Receive a parameter , Represents the number of decimal places in the result .
toPrecision()
Method will return the most reasonable output according to the situation , It could be a fixed length , It could also be scientific counting . This method takes a parameter , Represents the total number of digits in the result .
let num = 99
console.log(num.toPrecision(1)) //"1e+2"
console.log(num.toPrecision(2)) //"99"
console.log(num.toPrecision(1)) //"1e+2"
isInteger()
Used to identify whether a value is saved as an integer . Sometimes , Decimal 0 It may make people mistakenly think that the value is a floating-point value .
console.log(Number.isInteger(1)) //"true"
console.log(Number.isInteger(1.00)) //"true"
console.log(Number.isInteger(1.01)) //"false"
String
Every String Objects all have one length attribute , Represents the number of characters in a string
concat()
Used to splice one or more strings into a new string . Any number of parameters can be accepted , So you can splice multiple strings at once .
3 A method for extracting substrings from strings P121
slice()、substr()、substring()
- All three methods return substrings of the string that called them , And both receive one or two parameters . The first parameter represents the starting position of the substring , The second parameter indicates where the substring ends .
- Yes
slice()
andsubstring()
for , The second parameter is where the extraction ends ( namely Before this position Characters will be extracted ). - Yes
substr()
for , The second parameter represents Number of substrings returned .
In any case , Omitting the second parameter means extracting to the end of the string .
let str = "hello world"
console.log(str.slice(3)) //"lo world"
console.log(str.substring(3)) //"lo world"
console.log(str.substr(3)) //"lo world"
console.log(str.slice(3,7)) //"lo w"
console.log(str.substring(3,7)) //"lo w"
console.log(str.substr(3,7)) //"lo worl"
When a parameter is negative , this 3 The behavior of the two methods is different .
slice()
Method treats all negative parameters as string length plus negative parameter valuesubstr()
Method takes the first negative parameter value as the length of the string plus the value , Convert the second negative parameter to 0.substring()
Method converts all negative parameter values to 0.
let str = "hello world"
console.log(str.slice(-3)) //"rld"
console.log(str.substring(-3)) //"hello world"
console.log(str.substr(-3)) //"rld"
console.log(str.slice(3,-4)) //"lo w"
console.log(str.substring(3,-4)) //"hell"
console.log(str.substr(3,-4)) //" "(empty string)
Sixth elements ,substring(3,0)
Equivalent to substring(0,3)
, Because this method will take the smaller parameter as the starting point , Take the larger parameter as the end point .
String location method
indexOf()
and lastIndexOf()
Two methods search for an incoming string from a string , And return the subscript ( If not , Then return to -1), The difference is that the former starts from the beginning of the string and then starts to look for , The latter starts looking forward from the end of the string .
Both methods can accept the second parameter , Indicates where to start the search .
let str = "hello world"
console.log(str.indexOf("o",6)) //7
console.log(str.lastIndexOf("o",6)) //4
String contains methods
3 A method for determining whether a string contains another string :startWith()
、endWith()
and incluedes()
, All return a Boolean value indicating whether it is included . The difference lies in
startWith()
The check starts with the index 0 Matches forendWith()
The check starts with the index(string.length - substring.length)
Matches forincludes()
Check the entire string
startWith()
、includes()
Receive the optional second parameter , Indicates where to start the search .
endsWith()
Receive the optional second parameter , Represents the position that should be treated as the end of a string . If you don't provide this parameter , So the default is string length .
trim() Method
This method creates a copy of the string , Before deleting 、 All spaces after , Return the result .
repeat() Method
This method takes an integer parameter , Represents how many times to copy a string , And then return the result of stitching all the copies .
padStart() and padEnd() Method
These two methods will copy the string , If the specified length is less than , Then fill the corresponding side with characters , Until the length condition is satisfied . The first parameter is length , The second optional parameter is the padding string , Default is space .
The optional second parameter is not limited to one character . If a string of multiple characters is provided , It will be spliced and truncated to match the length .
let str = "foo"
console.log(str.padStart(6)) //" foo"
console.log(str.padStart(9,".")) //"......foo"
console.log(str.padEnd(8,"bar")) //"foobarba"
console.log(str.padEnd(9,".")) //"foo......"
String case conversion
toLowerCase()
、toLocaleLowerCase()
、toUpperCase()
and toLocaleUpperCase()
Singleton built-in objects
Global
in fact , There are no global variables or global functions . Variables and functions defined in the global scope become Global Object properties .
window object
The browser will window The object time limit is Global Proxy for object , So all variables and functions declared in the global scope become window Properties of .
Math
min()
max()
Used to determine the maximum and minimum of a set of values
Math.ceil()
Method always rounds up to the nearest integerMath.floor()
Method always rounds down to the nearest integerMath.round()
Method perform roundingMath.fround()
Method returns the closest single precision value (32 position ) Floating point values represent
Math.random()
Method returns a 0~1 Random numbers in the range , Include 0 But does not contain 1
The first 6 Chapter , Collection reference type
Object
In object literal notation , The property name can be a string or a numeric value
let person = {
"name":"Frank",
"age":29,
5:true
}
This example will get a with attributes name
、age
and 5
The object of . ( Numeric properties are automatically converted to strings )
let person = {
} // And new Object() identical
console.log(person.name) //"Frank"
console.log(person["name"]) //"Frank"
There is no difference between the two ways of reading attributes . If the property name contains characters that may cause syntax errors , Or include keywords / When retaining words , You can use bracket Syntax .
Array
Create array
What's different from other languages is , Each slot in the array can store Any type The data of , It's also Dynamic size Of , It will grow automatically as data is added .
let colors = Array(3) // Create a containing 3 Array of elements
let names = Array("Greg") // Create one that contains only one element “Greg” Array of
ES6 New static methods for creating arrays from()
and of()
. from()
Is used to Class array structure Convert to array instance , and of()
Is used to A set of parameters Convert to array instance .
Use scenarios
from()
Multiple parameters of a function can be arguments Convert to a real arrayof()
Form an array according to the incoming data
Array space
const options = [,,,,,] // Create contains 5 Array of elements
ES6 Treat these vacancies as elements of existence , But the value is undefined
Array index
Array length
Attributes are unique in that , It's not read-only . By modifying the length
attribute , You can remove or add elements from the end of the array
Detect arrays
isArray()
Method
Copy and fill methods p143
Batch copy method fill()
, Fill array method copyWithin()
fill()
Method to fill all elements of an array from the start index to the end index with a fixed value , Does not include terminating index . Ignore out of array bounds 、 Zero length and opposite index range
const zeroes = [0,0,0,0,0]
zeroes.fill(5) // use 5 Fill the entire array
zeroes.fill(6,3) // use 6 Fill index is greater than or equal to 3 The elements of
zeroes.fill(7,1,3) // use 6 Fill index is greater than or equal to 1 And less than 3 The elements of
zeroes.fill(8,-4,-1) // use 8 The proposal offset index is greater than or equal to 1 And less than 4 The elements of
copyWithin()
Method to copy part of an array to another location in the same array , And back to it , Does not change the length of the original array .
Transformation method
valueOf()
What is returned is the array itself
toString()
Returns a comma separated string concatenated by the equivalent strings of each value in the array , in other words , For each value of the array, we call toString()
Method , Get the final string .
Stack method
Is a kind of the stack Last in, first out (LIFO) Structure , Insertion of data items ( be called push ,push) And delete ( be called eject ,pop) It only happens in one place on the stack , The top of the stack .
push()
Method to receive any number of parameters , And add them to the end of the array , Returns the latest length of the array .
pop()
Method is used to delete the last item of the array , At the same time, reduce the number of arrays length value , Returns the deleted item .
Queue method
Queue to ** fifo (FIFO)** Form restricted access . The queue adds data at the end of the list , But getting data from the beginning of the list .
shift()
Delete the first item of the array , And back to it unshift()
Add any number of values at the beginning of the array , Then return the new array length
Sorting method
reverse()
Method to reverse the array elements
sort()
Method , By default , Array elements are rearranged in ascending order . So ,sort()
Will call... On each item string()
Transformation function , Then compare the strings to determine the order .
let values = [0,1,5,10,15]
values.sort()
alert(values) //0,1,10,15,5
At first, the order of values in the array is correct , But the call sort()
Will follow the string form of these values ( String encoding order ) reorder .
Obviously this is not the most appropriate in most cases , So sort()
Method can receive a Comparison function , Used to determine which value should be at the top .
function compare (value1,value2){
if (value1 < value2) {
return -1
} else if (value1 > value2){
return 1
} else {
return 0
}
}
This comparison function can be applied to most data types , You can pass it as a parameter to sort()
Method
let values = [0,1,5,10,15]
values.sort(compare)
alert(values) //0,1,5,10,15
Comparison functions can also produce a descending effect , Just swap the return values .
In addition, the comparison function can also be abbreviated as an arrow function
values.sort((a,b) => a<b ? 1 : a>b ? -1 : 0)
If the elements of an array are numeric , This comparison function can also be written more simply , Because you can subtract the first value from the second value
function compare (value1,value2){
return value2 - value1
}
The comparison function returns less than 0、0 And greater than 0 The numerical , Therefore, the operation of sword technique can completely meet the requirements .
Operation method
concat()
Create a new array based on all the elements of the existing array , Used to connect arrays .
slice()
Used to create a new array containing one or more elements of the original array .( Crop out a part of the original array )
splice()
The main purpose is to insert... In the middle of an array 、 Replace 、 Remove elements . Returns an array , Contains elements deleted from the original array .
I've summarized one before slice
and splice
's post CSDN link
Iterative method
Each method receives two parameters : Functions that run with each term as an argument , And the optional action on the object as the function running context ( In the influence function this Value ).
The function passed to each method receives 3 Parameters : Array elements 、 The element index and the array itself .
every()
Run the incoming function for each item in the array , If you return for each function true, Then this method returns truefilter()
Run the incoming function for each item in the array , The function returns true Will form an array and returnforEach()
Run the incoming function for each item in the array , no return valuemap()
Run the incoming function for each item in the array , Returns an array of the results of each function callsome()
Run the incoming function for each item in the array , If the intention function returns true, Then this method returns true.
These methods do not change the array that calls them .
Merging method
reduce()
and reduceRight()
Both methods iterate over all items of the array , And on this basis, build a final return value .
reduce()
Method starts from the first item of the array and traverses to the last item ,reduceRight()
Traverse from the last item to the first item .
Map
ES6 New features ,Map Is a new set type , It brings real keys to the language / Value storage mechanism .
Use new Key words and Map The constructor can create an empty map
const m = new Map(),
Initialize the instance while creating
const m1 = new Map({
["key1","val1"],
["key2","val2"],
["key3","val3"],
});
alert(m1.size) //3
After initialization , have access to set()
Method to add key value pairs . You can also use get()
and has()
The query , Can pass size
Property to get the number of key value pairs in the map , You can also use delete()
and clear()
Delete value .
And Object The difference is ,Object Only numerical values can be used 、 String or symbol as key ,Map You can use any JS Data type as key .
choice Object still Map P168
Memory footprint
Given a fixed size of memory ,Map It's about as good as Object More storage 50% The key/value pair
Insertion performance
If the code involves a large number of inserts , So clearly Map Better performance
Search speed
If a lot of operation code is involved , Then in some cases, you may choose Object Better
Delete performance
For most browser engines ,Map Of
delete()
Operations are faster than insert and find . If the code involves a large number of deletions , Then there is no doubt that we should choose Map
Set
Set In many ways, it is more like strengthening Map, Because most of them API And behavior are common .
const m = new Set() // Create an empty set
const s1 = new Set(["val1","val2","val3"])
After initialization , have access to add()
Added value , Use has()
Inquire about , adopt size Get the number of elements , And the use of delete()
and clear()
Remove elements
The first 7 Chapter , Iterators and generators
Iterator pattern Describes a solution , That is to say, some structures can be called **“ Iteratable object ”**, Because they achieved formal Iterable Interface , And you can use iterators iterator consumption .
Realized Iterable Built in type of interface :
- character string
- Array
- mapping
- aggregate
- arguments object
- NodeList etc. Dom Collection types
Native language features that receive iteratable objects include :
- for-of loop
- Array structure
- Extension operators
- Array.from()
- Create set
- Create mapping
- Promise.all() Received by promise Composed of iterable objects
- Promise.race() Received by promise Composed of iterable objects
- yield* The operator , Use... In the generator
iterator protocol
iterator API Use next()
Method traverses data in an iteratable object , Every successful call next()
, Will return to one IteratorResult object , It contains the next value returned by the iterator .
next()
Method contains two properties :done and value.
- done It's a Boolean value , Indicates whether it can be called again
next()
Get the next value .done:true The state is called “ Run out of ”. - value Contains the next value of the iteratable object (done by false when ), perhaps undefined(done by true when ).
As long as the iterator arrives done:true state , Subsequent calls next()
It always returns the same value
Instances of different iterators are not related to each other , Only iteratable objects are traversed independently :
let arr = ['foo' , 'baz'];
let iter1 = arr[Symbol.iterator]();
let iter2 = arr[Symbol.iterator]();
console.log(iter1.next()); //{done:false, value:'foo'}
console.log(iter2.next()); //{done:false, value:'foo'}
console.log(iter1.next()); //{done:false, value:'bar'}
console.log(iter2.next()); //{done:false, value:'bar'}
An iterator is not bound to a snapshot of an iteratable object at a certain time , Just use a cursor to record the mileage of traversing an iteratable object . If the iteratable object is modified during the iteration , So the iterator will also reflect the corresponding changes .
generator
The generator is in the form of a function , The function name is preceded by an asterisk (*) Indicates that it is a generator . * The left and right spaces are irrelevant .
Arrow functions cannot be used to define generator functions
Calling the generator function produces a Generator object , The generator object is initially in a suspended state , have next() Method , Calling this method causes the generator to start or resume execution .
Generator functions are only called the first time next() Method is executed .
adopt yield Interrupt execution
yield Keyword can make the generator stop and start execution , It is also the most useful place for generators .
The generator function encountered yield Keyword will be executed before . After meeting this keyword , Execution will stop , The state of the function scope is preserved . Generator functions that stop execution can only be executed by calling next() Method to resume execution .
function * generatorFn(){
yield;
}
let generatorObject = generatorFn();
console.log(generatorObject.next()); //{done:false, value:undefined}
console.log(generatorObject.next()); //{done:true, value:undefined}
here yield The keyword is a bit like the middle return statement of a function , The value it generates will appear in next() Method return object .
function * generatorFn(){
yield 'foo';
yield 'bar';
yield 'baz';
}
let generatorObject = generatorFn();
console.log(generatorObject.next()); //{done:false, value:'foo'}
console.log(generatorObject.next()); //{done:false, value:'bar'}
console.log(generatorObject.next()); //{done:true, value:'baz'}
The execution flow inside the generator function is scoped for each generator object . Call... On a generator object next() It doesn't affect other generators .
yield Keywords can only be used inside generator functions , Using it in other places will throw an error ,yield Keywords must be directly in the generator function definition .
Terminate generator early
return()
Unlike iterators , All generator objects have return() Method , As long as it's closed , Can't recover . Subsequent calls next() Will be displayed done:true state .
throw()
throw() Method will inject a supplied error into the generator object during the pause time . If the error is not handled , The generator will shut down .
however , Add generator function Inside Handled this error , So the generator doesn't shut down , And it can resume execution . Error handling will skip the corresponding yield, So in this case, a value is skipped .
The first 8 Chapter , object 、 Class and object oriented programming
Merge objects
ES6 Specifically for merging objects Object.assign()
Method . This method takes a target object and one or more source objects as parameters , Then the enumerable and self owned properties in each source object are copied to the target object . Properties with strings and symbols as keys are copied .
let dest,src,result;
// Simple replication
dest = {
};
src = {
id:'src'};
result = Object.assign(dest, src);
// Object.assign Modify the target object , It will also return the modified target object
console.log(dest === result); //true
console.log(dest !== src); //true
console.log(result) //{id:src}
console.log(dest); //{id:src}
Object to deconstruct
let person = {
name:'Matt';
age:27;
}
let{
name:personName , age:personAge} = person;
console.log(personName); //Matt
console.log(personAge); //27
null and undefined Can't be deconstructed , Otherwise, an error will be thrown .
Constructors
By convention , The first letter of the constructor name should be capitalized .
Inside the constructor this Assigned to this new object ( namely this Point to a new object )
Functions on different instances of the same constructor have the same name but are not equal , To solve this problem , Sure Move the function definition outside the constructor .
Archetypal model
Each function creates one prototype attribute , This property is an object , Contains properties and methods that should be shared by instances of a specific reference type . actually , This object is the prototype of the object created by calling the constructor . The advantage of using prototype objects is , The properties and methods defined on it can be shared by object instances .
By default , All prototype objects are automatically given a name called constructor Properties of , Refers back to the constructor associated with it .
There is a direct connection between instances and constructor prototypes , But there is no... Between instance and constructor .
Object The prototype of the prototype is null
console.log(Person.prototype.__proto__ === Object.prototype) //true
console.log(Person.prototype.__proto__.constructor === Object) //true
console.log(Person.prototype.__proto__.__proto__ === null) //true
Two instances created by the same constructor share the same prototype object .
Prototype level
When accessing properties through objects , The search starts with the name of the attribute . The search starts with the object instance itself , If the given name is found on this instance , The value corresponding to the name is returned . If this property is not found , The prototype will search the object along the pointer , Then find the attribute on the prototype object , And then return the corresponding value .
Use delete The operator can completely delete this attribute on the instance , This allows the identifier resolution process to continue searching for prototype objects .
hasOwnProperty()
Method is used to determine whether a property is on an instance or a prototype object
in The operator returns when the specified property is accessible through the object true, Whether the attribute is on an instance or prototype .
As long as you can access... Through objects ,in The operator returns true, and hasOwnProperty()
Returns... Only if the property exists on the instance true. therefore , as long as in Operator return true And hasOwnProperty() return false, This indicates that the attribute is a prototype attribute .
To get all enumerable instance properties on an object , have access to Object,keys()
Method .
Object iteration
Object.values()
Returns an array of object values
Object.entries()
Returns an array of key value pairs
边栏推荐
猜你喜欢
How to implement a custom jdbc driver in only four steps?
Explain the differences and usage scenarios between created and mounted
Ctfshow SQL injection (211-230)
Powershell 加域 Add-Computer模块
Design system based on MVC using javeswingjdbc
C disk lossless move file
Crawler scrapy framework learning 1
Createanonymousthreadx passes parameters to anonymous threads
利用Javeswingjdbc基於mvc設計系統
Colab tutorial (super detailed version) and colab pro/pro+ evaluation
随机推荐
C # get all callable methods of WebService interface [webmethod]
Applet - uniapp realizes the functions of two-dimensional code picture pop-up and picture saving
Clear timer failure
[JS solution] leedcode 200 Number of islands
MySQL index
2022年氧化工艺操作证考试题库及模拟考试
Develop go using vscode
Little C's Notepad
Record a troubleshooting process - video call cannot be picked up
[JS solution] leedcode 117 Populate the next right node pointer II for each node
Read paper 20 together: spatiotemporal prediction of PM2.5 concentration by idw-blstm under different time granularity
[untitled]
利用Javeswingjdbc基於mvc設計系統
Applet version update
ES6 learning
Your one-on-one meetings are inefficient. You can do this!
2022 oxidation process operation certificate examination question bank and simulation examination
【JS解决】leedcode 200. 岛屿数量
第三方评论插件
Nodejs parsing get request URL string