Script element
attribute
- Async: downloads immediately, executes immediately, and does not block page loading. It can only be used for external scripts. Asynchronous scripts cannot modify the DOM
- Defer: Download immediately, the page is loaded and executed
DOMContentLoaded
Before performing - Crossorigin: Whether to allow cross-domain,
anonymous
To not carry a cross-domain request header,use-credentials
Is the carry request header - Integrety: compares the received resource with the specified encryption signature to verify integrity. If any inconsistency occurs, an error is reported and the script is not executed
- SRC: Sets the resource URL
- Type: Generally, the value is
'text/javascript'
Can be used only if the value is moduleimport/export
The characteristics of
- The script executes from the top down, blocking the page rendering
- Scripts that use external scripts cannot contain in-line scripts, otherwise in-line scripts are ignored
Dynamic script
Dynamic scripts are asynchronous by default, but not all browsers support the async property and must be set to synchronous in order to uniformly load script behavior
let script = document.createElement('script')
script.src = 'xxx.js'
script.async = false
document.body.appendChild(script)
Copy the code
Dynamic script resources are invisible to browser preloading and need to be preloaded manually
<link rel="preload" ref="xxx.js"></link>
Copy the code
Language foundation
variable
- Var function scope, let and const block-level scope
- Var has variable promotion, let and const have temporary dead zones
- The global variables declared by var on the window object are not declared by let and const
- Const declares a reference to a value that must be initialized immediately and cannot be modified
Const takes precedence over let. Var is not recommended
The data type
The typeof operator
The data type | value |
---|---|
Undefined | ‘undefined’ |
Number | ‘number’ |
String | ‘string’ |
Boolean | ‘boolean’ |
The Object or Null | ‘object’ |
Function | ‘function’ |
Symbol | ‘symbol’ |
Undefined
Undeclared variables and uninitialized variables both result in undefined, so it is necessary to initialize variables when they are declared
Null
Null represents an empty object pointer and defines an object variable to be initialized with NULL
Boolean
All values can be converted to Boolean using Boolean(), 0, ”, false, null, undefined, and NaN results false, and other results are true
Number
MIN_VALUE and number. MAX_VALUE indicate the maximum and minimum values, isFinite(Number) and true
IsNaN (value) is converted to NaN
Rule for Number:
- True to 1, false to 0
- Undefined turn NaN
- Turn null 0
- Number returns itself
- Strings containing only numbers and “” return numeric values, other nans
- ValueOf () is called first, and toString() is called if the result is NaN.
ParseInt (value, the base number of the argument 1) intercepts the beginning of numeric, +, and – to non-numeric positions, otherwise NaN
ParseFloat (value) numeric, +, and – start intercepts to non-numeric or invalid floating point positions, otherwise NaN
String
The read-only attribute length represents the length of the string.
ToString (the result of the base value) has this method except undefined and null, the same as String()
Symbol
TODO
Object
Class Object public methods:
Constructor
: Constructor of the current objectHasOwnProperty (property name)
: Whether the current attribute is on an instance of the objecta.isPrototypeOf(b)
: Whether A is the prototype object of BPropertyIsEnumerable property name
: Indicates whether a for-in enumeration is available for attributestoString()
toLocaleString()
valueOf()
The operator
Unary operator
Call Number() first
An operator
Bitwise not ~ : the result is the inverse of the number, and the result is negative. -1 bitwise and & : the result is 1 only when the corresponding bits are 1. Bitwise or | : The result is 0 only when the corresponding bits are 0
Boolean operator
The logical not! : first call Boolean () to take on logic or | | : first the Boolean (), meet true is returned the operand logic and && : first call Boolean (), met false returns the operands
Addition, subtraction, multiplication and division operators
+-*/% The operand calls Number() first. If the operand is NaN, the result is NaN + and one side is string or concatenation
Relational operator
First call Number() and then compare the sizes. Compare character encodings if both operands are strings.
Equality operator
== operator rules:
- Implicit type conversions are performed
- undefined==null
- Object compares whether the object is the same
The === operator performs strict equality comparisons
statements
For-in statements only loop through object instances and stereotypes with non-symbol attributes
for(letThe property nameinObject){loop body}Copy the code
The for-of statement iterates over the elements in the order in which the iterable’s next() method produces the values
for(letThe property nameofIterable){body of loop}Copy the code
The label statement can be executed with break and continue
start: for (var i = 0; i < count; i++) {
alert(i);
}
Copy the code
Variables, scope, and memory
Raw and reference values
Variables with original values are accessed by value, and variables with reference values are accessed by reference
Copying the original value is a copy of the variable to the new variable, the old and new variables do not interfere with each other; Copying a reference value is a pointer to a new variable that maps the old and new variables
Function arguments are passed by value
function setName(obj){
obj.name = "zzz";
}
let person = new Object(a); setName(person)console.log(person.name); // 'ZZZ ', the function argument is passed by value, so the value of obj is a copy of the address, but the reference variable is accessed by reference, so the change will still be mapped to the original value
function setName(obj){
obj.name = 'zzz'
obj = new Object(a); obj.name ='zcw'
}
let person = new Object(a); setName(person)console.log(person.name); // 'ZZZ ', if the parameter is passed by reference, then the value of obj is mapped to the value of person, but there is no effect, so the parameter is passed by value
Copy the code
Execution context and scope
Each context has a variable object on which variables and functions defined in the context reside.
When code execution flows into a function, the context of the function is pushed into the context stack. When the function completes execution, the context stack pops up the function context, control is returned to the previous execution context, and the function context is destroyed.
When code in the context executes, it creates a scope chain of variable objects (which determines the order in which code at each level of context accesses variables and functions). The variable objects in the function context are AO active objects (only arguments objects initially).
Basic reference types
Date
New Date() passes no argument to create a Date object for the current Date, passing a Date object in milliseconds to create the timestamp.
Date.parse() passes a string representing the Date and returns the corresponding timestamp
Date.parse('4/27/2021')
new Date('May 1' 23202) Date.parse('May 23,2021')
Copy the code
Date.utc () passes year, month, day, hour, minute, second, and millisecond, returning the corresponding timestamp. Years will pass.
Date.now() returns the timestamp at which the method was executed
RegExp
model
- G: global, searches for all matches of the string
- I: Case insensitive
- M: Multi-line matching
- Y: Adhesion mode, which only finds the string part at the beginning of the lastIndex attribute of the re instance
- U: Enables Unicode matching
- S: indicates the metacharacter in dotAll mode. Matches any character (including \r or \n)
RegExp instance property
- Global: Whether the G flag is set
- IgnoreCase: Whether the I flag is set
- Unicode: Whether the U flag is set
- Sticky: Indicates whether the Y flag is set
- Multiline: Whether the M flag is set
- DotAll: Is the S flag set
- LastIndex: String position at the start of the next search
- Source: matching rules of regular expressions
- Flags: indicates the mode of the regular expression
let pattern = /\[bc\]at/i
console.log(pattern.global) // false
console.log(pattern.ignoreCase) // true
console.log(pattern.multiline) // false
console.log(pattern.lastIndex) / / 0
console.log(pattern.source) // "\[bc\]at"
console.log(pattern.flags) // "i"
Copy the code
RegExp instance method
Exec (string) : Finds a match, and if global or paste is not set, the first result is captured at a time
let text = 'mom and dad and baby'
let pattern = /a/gi
let matches = pattern.exec(text) // ["a", index: 4, input: "mom and dad and baby", groups: undefined]
matches = pattern.exec(text) // ["a", index: 9, input: "mom and dad and baby", groups: undefined]
Copy the code
Instance. test(string) : Returns true if the argument matches the pattern
RegExp constructor property
- Input: Indicates the last searched string
- LastMatch: The last matched text
- LastParen: Capture group last matched
- LeftContext: The text that appears to the left of lastMatch in the input string
- RightContext: Input string the text that appears to the right of lastMatch
let text = 'this has been a short summer'
let pattern = / (.). hort/g
if(pattern.test(text)){
console.log(RegExp.input) // this has been a short summer
console.log(RegExp.leftContext) // this has been a
console.log(RegExp.rightContext) // summer
console.log(RegExp.lastMatch) // short
console.log(RegExp.lastParen) // s
}
Copy the code
Original packing type
When a method is called on a primitive type, the following three steps are performed:
- Create an instance of the base wrapper type
- Invoke a method on the instance
- Destroy the instance immediately
'abc'.substr(1)
/ / is equivalent to
let s = new String('abc')
s.substr(1)
s = null
Copy the code
Characteristics of packaging type:
- The wrapper type is destroyed when the method is called
- The wrapper type typeof is both ‘object’, so all conversions are Boolean values of true
Boolean
Boolean wrapper type valueOf() returns true and false, toString() returns ‘true’ and ‘false’. Boolean wrapper type calls instanceOf Boolean return true. Boolean primitive type calls this return false
Number
ToFixed: Returns the value of the specified number of decimal places, which is automatically rounded toFixed: Returns the value of the scientific notation string containing the specified number of decimal places: IsInteger: This method is used to determine whether the value is an integer. If it is an integer, it returns true. 1.00 returns true
String
Characters of the method
CharCodeAt: returns the character encoding of the index position. CharAt: Returns the character encoding of the index position. FromCharCode (any Unicode encoding) : Converts the encoding to a string
Operation method
Concat (any character) : concatenates a copy of the original string with the argument slice(start, end) : Returns the substring from the start to the end, plus the character length substring(start, end) for negative numbers: Substr (start position, n) : Returns n characters at the start position. If the first argument is negative, the length of the character is added. If the second argument is negative, the value is 0
Location method
LastIndexOf (string, start position) : Search string from start position, return position, return negative number not found
Contains methods
StartsWith (string, start position) : Whether the start position begins with an argument. EndsWith (string, end position) : whether the end position endsWith argument one. Includes (string, start position) : from the start position to the end of the character, whether the parameter contains a character.
The trim method
Trim () : Creates a copy of the string, removing all Spaces before and after. TrimLeft () : Removes the space left of the copy. TrimRight () : Deletes the space to the right of the copy.
Copy the method
Repeat (n) : Copies characters n times and concatenates them
let s = 'na'
s.repeat(5) // nanananana
Copy the code
PadStart (length, fill character) : If the character is less than the length, fill two characters at the beginning of the parameter. If there is no parameter two, fill space. PadEnd (length, padding character) : If the character is less than the length, padding two characters at the end of the parameter, padding space if there is no two parameters.
String deconstruction
String prototypes expose the @@iterator method, which iterates over each character of the string, so you can use for-of to iterate.
let message = 'ab'
let StringIterator = message[Symbol.iterator]()
console.log(StringIterator.next()) // {value:'a',done:false}
console.log(StringIterator.next()) // {value:'b',done:false}
console.log(StringIterator.next()) // {value:undefined,done:true}
for(const s of 'abcde') {console.log(s)
}
Copy the code
String case conversion
ToLowercase () and toUpperCase ()
String matching method
Match (regular expression) : returns the same value as exec, which is an array with the first item being the matched string and the other two items being index and input search(regular expression) : Replace (regular expression, replacement character or function) : Replaces the matched character with a second argument
function htmlEscape(text){
return text.replace(/[<>"&]/g.function(match,pos,originalText){
switch(match){
case "<":
return "<"
case ">":
return ">"
case "&"
return "&"
case "\" ":
return """
}
})
}
htmlEscape("Hello world!
") // "< p class=" greeting" > Hello world! "
Copy the code
Split (string or matched re, array length) : Splits characters based on the result of the first argument, returning an array length no longer than argument two
let colorText = 'red,blue,green,yellow'
let colors1 = colorText.split(', ') // ['red','blue','green','yellow']
let colors2 = colorText.split(', '.2) // ['red','blue']
let colors3 = colorText.split(/ [^,] + /) // [',', ',', ',', ',', ',']
Copy the code
Collection reference type
The Object type
Object instances can be created by: New Object() and {} Object properties. Syntax or [‘ attribute name ‘]
Array type
Create an Array instance: new Array(multiple elements or Array length) and []
Array static method
Array.from() converts a class Array structure to an Array structure. The first argument is an array-like object (an iterable object) or an object with a length attribute and retrievable element, the second argument is an optional mapping function, and the third argument specifies the this value (not applicable in arrow functions).
const a1 = [1.2.3.4]
const a2 = Array.from(a1) // Shallow copy of array
const arrayLikeObject = {
0: 0.1: 1.2: 2.3: 3.length: 4
}
console.log(Array.from(arrayLikeObject)) / / [1, 2, 3, 4]
const a3 = Array.from(a1,function(x){return x**this.exponent},{exponent: 2})
Copy the code
An Array of () Array, a set of parameters can be converted to used in the Array of alternative before ES6. Prototype. Slice. Call this writing (the arguments)
Array.of(1.2.3.4) / / [1, 2, 3, 4]
Copy the code
Detection array
If there is only one global object (i.e. the web page does not have multiple frames), use instanceof. If there are multiple global objects, use array.isarray (value).
Iterator method
Keys () returns an iterator for array indexes, values() returns an iterator for array elements, and entries() returns an iterator for index/value pairs
const a = ['foo'.'bar'.'baz'.'qux']
const aKeys = Array.from(a.keys()) / /,1,2,3 [0]
const aValues = Array.from(a.values()) // ['foo','bar','baz','qux']
const aEntries = Array.from(a.entries()) // [[0,'foo'],[1,'bar'],[2,'baz'],[3,'qux']]
Copy the code
Copy and fill methods
Fill: Inserts a fill character into the start index to the end index of the array, no end index to the end index, negative index plus the array length, beyond the index boundary, zero length and the opposite direction are ignored
const zeroes = [0.0.0.0.0]
zeroes.fill(6.3.4) / /,0,0,6,0 [0]
zeroes.fill(6, -2, -1)/ /,0,0,6,0 [0]
zeroes.fill(6.10.15) // Out of bounds, ignore
zeroes.fill(6.4.2) // In the opposite direction, ignore
zeroes.fill(6.4.10) // the [0,0,0,0,6] section can be partially filled
Copy the code
CopyWithin shallow copies the contents of the specified index, and then populates them to the specified index position
Conversion method
ValueOf () : Returns the array itself. Join (Concatenation character) : Concatenates the array into a string separated by arguments. If not, it is a comma
Operation method
: concat () subjected to arbitrary parameter, add it to the back of the copy of the source array and array parameter if it is, will automatically draw, you can set the Symbol. IsConcatSpreadable to false to prohibit forced to draw an array
let colors = ['red'.'green'.'blue']
let colors2 = colors.concat('yellow'['black'.'brown'])
console.log(colors) // ['red','green','blue']
console.log(colors2) // ['red','green','blue','yellow','black','brown']
let moreNewColors = {
[Symbol.isConcatSpreadable]: false
length: 2.0: 'pink'.1: 'cyan'
}
let colors3 = colors.concat(moreNewColors)
console.log(colors3) // ['red','green','blue',['pink','cyan']]
Copy the code
Slice (the starting index, the ending index) : a copy of the source array index from the start, began to intercept, until the ending index, return to intercept array splice (the starting index, delete the length n, added value) : the original array index from the start position began to delete, delete item n, then the value behind the insert to the array, returns the array of delete
The stack method
Push () takes any number of arguments to add to the end and returns the length of the array. Pop () removes the last item of the array and returns the deleted item
Queue method
Unshift () takes any number of arguments to add to the beginning and returns the length of the array shift() removes the first item of the array and returns the deleted item
Sorting method
Reverse () reverses the array
Sort () sorts each item of the array by calling String() and can accept a comparison function, with parameters A and b representing the first and last items in the array, returning a positive number if it needs to be swapped, or a negative number otherwise
let values = [0.1.5.10.15]
values.sort(function(a,b){
return a-b // if a>b, then a-b is positive, so it is in ascending order. If return b-a, it is in descending order
})
Copy the code
Search and location methods
Strictly equal (===)
IndexOf searches for elements from the beginning or from argument 2, returns index if found, returns -1 if not found If not found, return -1 includes. If not found, return true. If not found, return false
Assertion functions
Each item in the find array calls the assertion function. If the assertion function returns true, it matches, and returns the matched item
const evens = [2.4.6]
evens.find((item,index,array) = >{
console.log(item,index.array)
return item === 4
})
Copy the code
Each item in the findIndex array calls the predicate function, which returns a true value indicating a match, and returns the index of the matched item
Merge method
Reduce iterates through each item of the array from left to right, using the result of the previous call as the initial value for the next call
let values = [1.2.3.4.5]
let sum = values.reduce((prev,cur,index,array) = >prev+cur)
console.log(sum) / / 15
Copy the code
ReduceRight (merge function, merge initial values) iterates through each item in the array from right to left, using the previous result as the initial value for the next call
An iterative approach
Each iteration method takes two arguments: the function that runs with each argument and the function this object
Every () runs on each item of the array, and returns true if each function returns true. Some () runs on each item of the array, and returns true if any function returns true. Filter () runs on each item of the array, The map() function runs on each item of the array and returns an array made up of the results of each function call. ForEach () runs on each item of the array and returns no value
Continuously updated…