- A reference value (object) is an instance of a particular reference type
- Reference types are structures that organize data and functionality together.
- Reference types are sometimes called object definitions because they describe the properties and methods their own objects should have.
- Objects are considered instances of a particular reference type. A new object is created by using the new operator followed by a constructor.
- A function is also a reference type.
1, the Date,
-
1970.1.1
-
Create: let now = new Date()
- The no-pass parameter is the current time
- The pass parameter is the number of milliseconds to be passed
-
Date.parse()
- Receives a string argument representing the date, attempting to convert to milliseconds
- “Month/day/year”
- “Name of month, day, year”
- The actual return value of the instance
- YYYY-MM-DDTHH:mm:ss:sssZ
- Does not indicate that the date returns NaN
- Call date.parse () directly to the Date constructor
- Receives a string argument representing the date, attempting to convert to milliseconds
-
Date.UTC()
- Returns a millisecond representation of the date
- Parameters: year, month (0-11), day, hour, minute, second, millisecond
- Pass it directly to the Date constructor and call date.utc () in the background
-
Date.now()
- Returns the number of milliseconds in which it was executed
1. Inheritance methods
- ToLocaleString () returns a time consistent with the local environment
- ToString () Date and time with time zone information
- ValueOf () returns a millisecond representation of the date
2. Date formatting method
- toDateString() “Mon May 24 2021”
- ToTimeString () “20:55:52 GMT+0800”
- toLocaleDateString() “2021/5/24”
- ToLocaleTimeString () “8:55:52 PM”
- toUTCString() “Mon, 24 May 2021 12:55:52 GMT”
Date/time component method
methods | instructions |
---|---|
getTime() | Return milliseconds of the date (valueOf) |
setTime(ms) | Set the milliseconds of the date to modify the entire date |
getFullYear() | Returns a 4-digit year |
setFullYear(year) | Set the year of the date to 4 bits |
getMonth() | The month 0 of the return date means January |
setMonth(month) | Set the month 0 of the date to January |
getDate() | Returns the day in the date |
setDate(date) | Sets the day in the date |
getDay() | Return day of the week 0 indicates Sunday |
getHours() | Returns when in the date |
setHours(hours) | Sets the time in the date |
getMinutes() | Returns the minute in the date |
setMinutes(minutes) | Sets the minute in the date |
getSeconds() | Returns seconds in the date |
setSeconds(seconds) | Sets the seconds in the date |
getMilliseconds() | Returns the milliseconds in the date |
setMilliseconds(ms) | Sets the milliseconds in the date |
2, the RegExp
-
Supports concise syntax to create let expression = /pattern/flags
- Pattern can be any simple or complex regular expression
- Flags to control behavior
- G Global mode, find everything
- I is case insensitive
- M Multi-line mode
- Y adhesion mode, looking only for strings after the start of lastIndex
- U Enable Unicode matching
- S dotAll mode, representing metacharacters, matches any character
-
It can also be created using constructors
let parttern1 = /[bc]at/i let parttern2 = new RegExp("[bc]at"."i") Copy the code
-
Both arguments need to be strings
-
Metacharacters require a secondary translation
/\[bc\]at/ -> "\\[bc\\]at"
/\.at/ -> "\\.at"
-
You can modify it selectively
const re1 = /cat/g const re2 = new RegExp(re1) const re3 = new RegExp(re1, "i") Copy the code
-
1. Instance properties
global
, Boolean value indicating whether the G flag is setignoreCase
, a Boolean value indicating whether the I flag is setunicode
, Boolean value indicating whether the U flag is setsticky
, Boolean value indicating whether the y flag is setlastIndex
, an integer that represents the starting position of the next search in the source stringmultiline
, a Boolean value indicating whether the M flag is setdotAll
, Boolean value indicating whether the S flag is setsource
, regular expression literal stringflags
The regular expression marks the string
2. Instance method
- Exec () is used with capture groups
- If a match is found, return the array of the first match information
- Returns null if not found.
- The returned array contains two additional attributes index and input
- Index is the starting position of the matching pattern in the string
- Input is the string to look for
- The first element matches the pattern of the entire string
- The second element is the first matching group, and the third element is the second matching group
- If the global tag is set, lastIndex searches backwards all the way
- The y adhesion tag (which only looks up at the lastIndex location) overrides the global tag, which can be set
- Test () takes a string argument and returns a Boolean value
- No matter how they are created, the inheritance methods toString() and toLocaleString() return literal representations.
- The valueOf() method returns the regular expression itself
Constructor properties
The full name | shorthand | instructions |
---|---|---|
input | The $_ | The string searched last |
lastMatch | $& | Last matched text |
lastParen | + $ | The capture group that was last matched |
leftContext | $` | Input The text that appears before lastMatch |
rightContext | $’ | Input Is the text that appears after lastMatch |
- Abbreviations are accessed with brackets
4. Model limitations
3. Original value packaging type
let s1 = "some text"
let s2 = s1.substring(2)
Copy the code
-
Why can a method be called if the original value is not an object?
-
Because the second line accesses string values in read mode:
-
Create an instance of String
let s1 = new String("some text")
-
Invoke a specific method on the instance
let s2 = s1.substring(2)
-
Destroy instance
s1 = null
-
-
-
Reference types differ from primitive value wrapper types in the life cycle of the object.
-
When a reference type is instantiated using new, the resulting instance is destroyed when it leaves scope.
-
The automatically created primitive value wrapper type exists only during the execution of the line of code that accesses it.
-
So you cannot add attribute methods to raw values at run time
let s1 = "some text" s1.color = "red" // Create and destroy console.log(s1.color)// undefined Copy the code
-
-
You can explicitly use the Boolean, Number, String constructors to create primitive value wrapper objects.
- Calling Typeof returns object
- Is converted to a Boolean value true?
-
The Object constructor, as a factory method, returns the corresponding primitive value wrapper type based on the incoming value type.
let obj = new Object("some text") obj instanceof String // true Copy the code
-
The constructor created with new is not the same as calling the transition function of the same name
let val = "25" let number = Number(val) let obj = new Number(val) typeof number // "number" typeof obj // "object" Copy the code
1, Boolean
-
The type of reference to a Boolean value
-
Override the valueOf() method to return the original true/false value
-
ToString () returns the string “true”/”false”
-
Boolean object, myth
let falseObj = new Boolean(false) let res = falseObj && true res // true let falseVal = false let res = falseVal && true res // false Copy the code
-
Typeof original value: ‘Boolean’, typeof reference value: ‘object’
-
Boolean objects are instances of Boolean types.
let falseObj = new Boolean(false) let falseVal = false typeof falseObj // "object" typeof falseVal // "boolean" falseObj instanceof Boolean // true falseVal instanceof Boolean // false Copy the code
2, the Number
- The reference type of a value
- Overrides valueOf(), toLocaleString(), toString() methods
- ValueOf () returns the original value represented by the Number object
- The toString() method argument can be a radix and returns a numeric string in the corresponding radix (base) form
- The toFixed() method returns a value containing the specified number of decimal placesNumeric string
- If less, 0 is added, if more, rounded
- ToExponential () returns to the representation of the s&T methodNumeric string
- The parameter represents the number of bits in the result
- ToPrecision () returns the most reasonable output depending on the situation.
- Determine whether toFixed() or toFixed() is called based on value and accuracy
let numberObj = new Number(10)
let numberVal = 10
typeof numberObj // "object"
typeof numberVal // "number"
numberObj instanceof Number // true
numberVal instanceof Number // false
Copy the code
- IsInteger () method
- Number.isinteger () identifies whether a value is saved as an integer
- All zeros are not considered floating-point values
- Number.MIN_SAFE_INTEGER /Number.MAX_SAFE_INTEGER
- Binary values in the range can represent an integer value
- Out of range may represent different values
- Number.issafeinteger ()
3, the String
- The type of reference to a string
- ValueOf (), toLocaleString(), and toString() all return the original value
- The length property looks at the number of characters. Double-byte characters are also counted as single characters
1. JavaScript strings
let msg = "abcde"
-
CharAt () returns the character at the given index position
message.charAt(2) //"c"
-
CharCodeAt () returns the character encoding of the code element
message.charCodeAt(2) //99
-
FromCharCode () return code creates string characters
String. FromCharCode (97,98,99,100,101) / / "abcde"
Normalize () method
3. Operation method of string
- concat()
- Concatenate one or more strings into a new string
- The original value remains the same
- Any number of parameters
- Equivalent to +
- slice()
- Equivalent to array slice
- Positive numbers are the same as substring()
- A negative number is equal to the length of the string plus a negative number
- Intercepts characters from XXX to XXX
- Original value of the same
- The second argument is omitted to the tail
- substring()
- Positive numbers are the same as slice()
- Negative numbers all go to 0
- Intercepts characters from XXX to XXX
- Original value of the same
- The second argument is omitted to the tail
- A smaller number is the starting point and a larger number is the ending point
- substr()
- The first argument starts intercepting a string of the length of the second argument
- The negative value of the first argument is the length of the string plus a negative number
- The second argument turns negative to 0
- Original value of the same
- The second argument is omitted to the tail
4. String position method
Searches for the incoming string from the string and returns the position, -1 if not found
- indexOf()
- Find substrings starting at the beginning of the string
- The second parameter indicates the location to start searching
- lastIndexOf()
- Find substrings starting at the end of the string
- The second parameter indicates the location to start searching
// Find all target strings
let str = 'Lorem ipsum dolor sit amet'
let positinos = new Array(a)let pos = str.indexOf("e")
while(pos > -1){
positions.push(pos)
pos = str.indexOf("e", pos + 1)
}
positions / / [24] 3,
Copy the code
5. String containing method
-
startsWith()
- Checks for matches starting at 0
- The second parameter indicates where to start the search
-
endsWith()
-
Checking the trailing string
-
The second argument represents the trailing position
let msg = 'foobarbaz' msg.endsWith('bar') // false msg.endsWith('bar'.6) // true Copy the code
-
-
includes()
- Check the entire string
- The second parameter indicates where to start the search
6. Trim () method
- Delete before and after Spaces
- I don’t change the original value
- TrimLeft () and trimRight(), respectively
7. Repeat () method
- Receives an integer argument indicating how many times a character is copied
- I don’t change the original value
8. PadStart () and padEnd() methods
- I don’t change the original value
- If less than the specified length, add characters before and after
- The length of the first argument
- The second argument fills the string, with a default space
- The second argument does not limit one character. If there are more than one character, it will be concatenated to match
String iteration and structure
-
The string prototype exposes an @@iterator method that iterates over each character of the string
let msg = 'abc' let iterator = msg[Symbol.iterator]() iterator.next() //{value: "a", done:false} iterator.next() //{value: "b", done:false} iterator.next() //{value: "b", done:false} iterator.next() //{value: undefined, done:true} Copy the code
-
This iterator can be used in for-of to access each character sequentially
for(const c of 'abc') {console.log(c) } Copy the code
-
With this iterator, a string can be deconstructed by the destruct operator.
let msg = "abcde" [...msg] // ["a", "b", "c", "d", "e"] Copy the code
String case conversion
- Change toLowerCase() toLowerCase
- ToUpperCase () is capitalized
11. String pattern matching method
-
match()
- Essentially the same as the exec() method, which returns an array
- The argument can be a regular expression string or a RegExp object
let text = "cat, bat, sat, fat" let pattern = /.at/ // Equivalent to pattern.exec(text) let matches = text.match(pattern) matches.index / / 0 matches[0] // "cat" pattern.lastIndex / / 0 Copy the code
-
search()
- The argument can be a regular expression string or a RegExp object
- Returns the index of the first matching position of the pattern, -1 if not found
- Always match backwards from the beginning of the string
let text = "cat, bat, sat, fat" let pos = text.search(/at/) pos / / 1 Copy the code
-
replace()
- String substitution
- Two parameters
- The first argument can be a RegExp object or a string (not converted to a regular expression)
- The second argument can be a string or a function
- If the first argument is a string, only the first substring is replaced. To replace all the first parameters must be regular expressions with global flags
let text = "cat, bat, sat, fat" let result = text.replace("at"."ond") result // "cond, bat, sat, fat" result = text.replace(/at/g."ond") result // "cond, bond, sond, fond" Copy the code
-
When the second argument is a string, there are several special sequences
Character sequence Replace text $$ $ $& Matches the entire pattern substring, lastMatch $’ Matches the string following the substring, rightContext $` Matches the string before the substring, leftContext $n Matches the NTH capture group string, n is 0-9 no capture group is an empty string $nn Matches the NNTH capture group string, n is 01-99 no capture group is an empty string let text = "cat, bat, sat" result = text.replace(/(.at)/g."word($1)") result //"world(cat), world(bat), world(sat)" Copy the code
-
The second argument is a function
- You get three arguments
- A string that matches the entire pattern
- The starting position of the match in the string
- Entire string
- Return a string
- What should I replace it with
function htmlEscape(text){ return text.replace(/[<>"&]/g.function(match, pos, originalText) { switch(match) { case "<": return "<"; case ">": return "$gt;"; case "&": return "&"; case "\" ": return """; }})}Copy the code
- You get three arguments
-
split()
- Splits the string into arrays based on the delimiter passed in
- The delimiter can be a string or a RegExp object
- The second parameter is the array size
let colorText = "red,blue,green" colorText.split(",") // ["red", "blue", "green"] colorText.split(",".2) // ["red", "blue"] colorText.split(/ [^,] + /) // ["", ",", ",", "] Copy the code
LocaleCompare () method
- Compare two strings, returning one of the following three values
- In alphabetical order, the string should precede the string arguments and return a negative value, usually -1
- Equal returns 0
- In alphabetical order, the string should follow the string arguments and return a positive value, usually 1
13. HTML methods
Dynamically generate HTML tags
4. Singleton built-in objects
- Built-in object: Any object provided by an ECMAScript implementation, independent of the host environment, that exists at the beginning of execution of an ECMAScript program.
1, the Global
- The Global object acts as a back-of-the-envelope object for properties and methods that do not belong to any object.
- In fact, variables and functions defined in the Global scope become properties of the Global object.
1. URL encoding method
-
Use to encode the Uniform Resource Identifier for passing to the browser
-
encodeURI()
- Encodes the entire URI
- Special characters for input URL components are not encoded
- Such as colon, slash, question mark, pound sign
-
encodeURIComponent()
- The commonly used
- Encode individual components in the URI
- All non-letters are replaced with the encoding format
-
DecodeURI (), decodeURIComponent()
-
Instead of escape(), unescape()
2, the eval ()
- Receives the parameter, an ECMAScript string to be executed
- The code being executed has the same chain of scopes as the context
- Functions and variables can be defined for external use (non-strict mode)
- careful
3. Global object properties
- Special values
- Undefined, NaN, Infinity
- The constructor
- Object, Array, Function,Boolean,String, Number, Date, RegExp, Symbol, Error, EvalError, RangeError, ReferenceError,SyntacError,TypeError,URIError
4. Window object
-
The browser implements the Window object as a proxy for the Global object
let global = function() { return this} ()Copy the code
2, Math
- It is much faster than a direct implementation because of more efficient implementations and processor instructions.
- But the accuracy will vary from environment to environment
1. Math object properties
attribute | instructions |
---|---|
Math.E | The base e of the natural logarithm |
Math.LN10 | Logarithm of a natural number base 10 |
Math.LN2 | Logarithm of a natural number base two |
Math.LOG2E | Log base two of e |
Math.LOG10E | Log base 10 of E |
Math.PI | The value of PI |
Math.SQRT1_2 | The square root of 1/2 |
Math.SQRT2 | Square root of 2 |
2. Min () and Max () methods
- Determine the minimum and maximum values in a set of values
- Arrays can be extended with the extension operator…
3. Rounding method
- Math.ceil() is always rounded up to the nearest positive number
- Math.floor() is always rounded down to the nearest positive number
- Math.round() performs rounding
Math.fround() returns the closest single-precision (32-bit) floating-point representation of the value
4. Random () method
- Returns a random number in the range 0 to 1, including 0 but not including 1
/ / return 1 ~ 10
number = Math.floor(Math.random()* 10 + 1)
Copy the code
- Encryption is recommended to use window. The crypto. GetRandomValues ()
5. Other methods
-
Math.abs(x) returns the absolute value of x
-
Math.pow(x, power) returns the power of x
-
Math.sqrt(x) returns the square root of x