1. Array destruction
const arr = ["1","2","3"] let a,b,c // Deconstruction and assignment// Assign the first element of the array to the first variable, assign the second element to the second variable, and so on in turn [a,b,c] = arr (a,b,c) // 1 2 3
// Declare variables at the same timelet [a,b,c] = ["1","2","3"] (a,b,c) // 1 2 3
// If the number of variables is greater than the number of elements, the excess variable part is assigned to undefinedconst arr = ["1","2","3"] let [a,b,c,d] = arr (a,b,c,d) // 1 2 3 undefined
// Default value. If the variable declares the default value and deconstructs it to undefined, the default value will be used, otherwise the corresponding element will be used.const arr = ["1","2","3"] let [a,b,c=10,d=11] = arr (a,b,c,d) // 1 2 3 11
// When deconstructing an array, you can use... to get the remaining elements const arr = ["1","2","3","4","5"] // The first element is assigned to a, the second element is assigned to b, and the rest are assigned to clet [a,b, ...c] = arr (a) // 1 (b) // 2 (c) // ['3','4','4']
// Deconstruct multidimensional arraysconst arr = [[1,2,3],[4,5,6]] let [[a,b,c],obj] = arr (a,b,c) // 1 2 3 (obj) // [4,5,6]
2. Object destruction
const user = {"name":"q",age:18} // Declare variables and deconstruct objects at the same timelet {name,age} = user (name,age) // q 18
// Declare the variable first, then deconstruct the objectconst user = {"name":"q",age:18} let name,age ({name,age} = user) // {} is a code block in js, so you need to use() outside(name,age) // q 18
const user = {"name":"q",age:18} // If the variable name does not match the attribute name, deconstructed to undefinedlet {a,b} = user (a,b) // undefined undefined // You can alias the variable and then deconstruct it// You can alias the variable and set the default valuelet {name:c,age:d=20} = user (c,d) // q 18
3. Object serialization
Objects in JS are always present in the computer's memory when used. Serialization refers to converting an object into a format that can be stored. In JS, the serialization of an object is usually converted into a string (JSON string)
const user = {name:"l",age:18} // Convert an object to a json stringconst strUser = (user) (strUser) // Convert a json string to a js objectconst objUser = (strUser) (objUser)
Notes on writing JSON:
There are two types of JSON strings:
- JSON object {}
- JSON array []
The attribute name of a JSON string must be enclosed in double quotes.
Attribute value (element) that can be used in JSON
- Number (Number)
- String must be double quoted
- Boolean
- Null value (Null)
- Object {})
- Array (Array [])
// Use json to complete deep copy, convert the object into a string, and then convert the string into a new objectconst strUser = (user) const objUser = (strUser)
Map is used to store the data of the key-value structure (key-value)
The data stored in the Object can be considered as a key-value pair structure
The main differences between Map and Object:
- The attribute name in the Object can only be a string or symbol. If a property name of another type is passed, the JS interpreter will automatically convert it to a string.
- Any type in a map can be called a key of data
4.1map usage
const info = new Map() // Set key-value pairs("name","l") ({},"a") (NaN,"b") (info) // Map(3) { 'name' => 'l', {} => 'a', NaN => 'b' } // Current map size() // 3 // Get all keys of map(()) // [Map Iterator] { 'name', {}, NaN } // Get all the values of map(()) // [Map Iterator] { 'l', 'a', 'b' } // Check whether the map contains the specified key, including true, otherwise false((NaN)) // true // Get the specified element through key(("name")) // l // Delete elements("name") (info) // Map(2) { {} => 'a', NaN => 'b' } // Clear map() (info) // Map(0) {}
4.2map conversion
const info = new Map() ("name","l") ({},"a") (NaN,"b") // Use Convert map to arrayconst arr = (info) (arr) // [ [ 'name', 'l' ], [ {}, 'a' ], [ NaN, 'b' ] ]
const arr = [["name",1],["age",2]] // Convert a 2D array to a mapconst map = new Map(arr) (map) // Map(2) { 'name' => 1, 'age' => 2 }
4.3 traversal map
const info = new Map() ("a",1) ("b",2) // Method 1for (const entry of info){ const [key,value] = entry (key,value) } for (const [key,value] of info){ (key,value) } // Method 2 ((key,value)=>{ (key,value) })
- Set is used to create a collection
- Its function is similar to arrays, the difference is that duplicate data cannot be stored in Set
// Create a collectionconst set = new Set() // Add data, if the element to be added already exists in the collection, it will not be added("a") ("b") // Get the size of the collection() // 2 // Check whether the set contains the specified element, including true, otherwise false(("a")) // true // Read the specified element - you need to convert set into an array and then read through the subscriptconst arr = [...set] (arr[0]) // a // Delete elements("b") // traverse the collectionfor (const v of set){ (v) }
// Create a collection through an array, and based on the uniqueness of the collection elements, the array will be deduplicated based on the array's uniqueness. const arr = [1,2,3,4,4,1,1,5] const set = new Set(arr) (set) // Set(5) { 1, 2, 3, 4, 5 }
Math is a tool class that provides some constants and methods for mathematical operations.
Complete usage
// Constant Pi() // 3.141592653589793 // Find the absolute value of a number((-123)) // 123 // Find the minimum value among multiple values((1, 2, 3)) // 1 // Find the maximum value among multiple values((1,2,3)) // 3 // Find the power of the specified value((2,3)) // 8 // Find the square root of a number((4)) // 2 // Round down((1.5)) // 1 // Round up((1.5)) // 2 // Rounding((3.5)) // 4 // Remove decimal places((3.5)) // 3 // Generate random floating point numbers between 0~1, not including 0 and 1(()) // 0.11258771607929718 // Generate random integers between 0 and 5// Range is 0~1, *5 expands the range by 5 times 0~5. The default does not include 0 and 5, and then rounds, including 0 and 5 according to rounding((() * 5)) // Generate random numbers in any range x ~ y/* Random number between 1 and 6 The range is expanded by 5 times, 0~5, and then +1 is 1~6, and the random decimals are rounded, including 1 and 6 */ ((() * 5 + 1)) // Integer between 11 and 20// [0,1] -> [0,9] -> [0+11,9+11] // Write the part after the + sign first, 11, 20-11=9((() * 9 + 11)) // Decide whether the left and right values are included according to the rules of rounding, evidence collection and other methods
All time-related data in JS are represented by Date objects
Complete usage
7.1Date usage
// Create an object of the current timelet date = new Date() (date) // 2024-10-30T10:48:29.454Z // Create a specified time object - year, month (starting from subscript 0), day, hour, minute, seconds, millisecondsdate = new Date(2024,9,30,13,13,13,13) (date) // 2020-01-01T05:13:13.000Z // Create an object for the specified time - through the time string - year - month - day Time: minute: secondsdate = new Date("2024-10-30 12:00:00") (date) // 2024-10-30T04:00:00.000Z // Create an object with a specified time - by time stampdate = new Date(1730265193013) (date) // 2024-10-30T05:13:13.013Z // Get the year of the time object(()) // Get the month of the time object - the index of the month is returned, and the index starts from 0(()) // Get the day of the time object(()) // The day object is the week (0-6) 0 represents Sunday(()) // Return the time stamp of the current date object(()) // Return the time stamp of the current time(())
7.2Date formatting
let date = new Date() // Convert date to local time format stringlet time = () (time) // 10/31/2024 // Convert time to local time format stringtime = () (time) // 10:32:05 AM // Convert date and time to local time format stringtime = () (time) // 10/31/2024, 10:32:50 AM // Convert date and time to specified region, format string - specified country timetime = ( "en-US", //Specify language and country {dateStyle: "full", timeStyle: "full"} // dateStyle // timeStyle Time Style // full // long // medium // short // hour12 Whether to use a 12-hour value // true // false // Weekday weekday display // long // short // narrow // // year // numeric // 2-digit ) (time)
8. Packaging
In JS, in addition to directly creating the original value, you can also create objects with original value
// New String() can create an object of String type// New Number() can create an object of Number type// New Boolean() can create objects of Boolean type // Note: Never do this, the object is created in this way and cannot be compared with the original value let str = new String("hello world") let num = new Number(10) let bool = new Boolean(true) = 100 // Set properties for num objects (str) // [String: 'hello world'] (num) // [Number: 10] () // 100 (bool) // [Boolean: true] (num === 10) // false
Packaging:
- There are 5 packaging classes in JS
- String --> String wraps as String objects
- Number --> Value wrapped as Number object
- Boolean --> Boolean value is wrapped as a Boolean object
- BigInt --> Large integer wrapping as BigInt object
- Symbol --> Symbol wraps as Symbol objects
A primitive value can be wrapped into an object through a wrapper class
When we call a method or property on a primitive value, the JS interpreter will temporarily wrap the original value into the corresponding object, and then call the attribute or method of the object
// Original valuelet str = "hello world" // Adding attributes to the original value will convert the original value into a one-time temporary original value object = "11111" // Assign and read two calls are two temporary raw value objects and cannot be read through this method() // undefined let num = 100 // There is no method for the original value number. When calling the method, the num is temporarily converted into a number object and the toString method of the number object is called.num = ()
Since the original value will be temporarily converted to the corresponding object, this means that the methods in the original value object can be called directly through the original value
// The essence of a string is a character array, hello-->["h","e","l","l","l","0"] let str = "hello" // You can manipulate strings through some methods of manipulating arrays // Index read characters - no negative indexing(str[0]) // h // traverse stringsfor (let char of str){ (char) } // Get the string length() // 5 // Get strings based on index, and can accept negative indexes((-1)) // o // Index read characters - no negative indexing((0)) // h // Used to concatenate two or more strings and return a new string((" world"," !")) // hello world ! // Check whether a string contains something, return true or false(("ll")) //Detection of all strings true(("h",2)) // Start to detect false from subscript 2 // Check the first location of the specified character(("l")) // 2 // Check the last occurrence of the specified character(("l")) // 3 // Check whether the string starts with the specified content(("he")) // true // Check whether the string ends with the specified content(("o")) // true // Complease the string If the length of the string is not enough to specify the length, start with the beginning and return a new string without specifying the complement character, the default is empty((7,"0")) // 00hello // Complement the string If the length of the string is not enough to specify the length, add 0 from the end and return a new string((8,"0")) // hello000 // Replace a specified content in the string with a new string and return a new string(("l","a")) // healo // Replace all specified content with a new string and return a new string(("l","a")) // heaao // Slice the string, close the left and open the right((1,3)) // el // Intercept the string, close the left and open the right((1,3)) // el // Split a string into an array, and the parameters specify the character interval to split in which character(("")) // [ 'h', 'e', 'l', 'l', 'o' ] // Convert string to lowercase(()) // hello // Convert string to uppercase(()) // HELLO // Remove the beginning and end spaces(()) // Remove the start space(()) // Remove the end space(())
9. Regular Expressions
- Regular expressions are used to define a rule
- Through this rule, the computer can check whether a string complies with the rules or extract the content of the string complies with the rules.
- Regular expressions are also an object in JS, so to use regular expressions, you need to create the object of the regular expression first.
9.1 Creating a regular expression object
// Create a regular expression object through the constructor, RegExp() receives two string parameters 1. Regular expression 2. Match pattern// The reason for string escape, please pay attention to escape when writing expressionslet regObj = new RegExp("\\w","i") // Create a regular expression object using literals, /Expression/Match pattern// No need to consider escaping issues when creating literalslet reg = /\w/i let reg2 = new RegExp("a") // test method: get specified string test whether there is a part that matches the regular expression re(("abc")) // The string str expression a str contains a and returns true
9.2 Regular Expression Syntax
// Most characters can be written directly in regular expressions// | Indicate or in regular expressions // Is there abc or bcd stringlet re = /abc|bcd/ // [] represents character set // Whether a string contains any letters in the character set is equivalent to a | b | cre = /[abc]/ //Arbitrary lowercase lettersre = /[a-z]/ // Any capital lettersre = /[A-Z]/ //Arbitrary upper and lower case lettersre = /[a-zA-Z]/ // Any numberre = /[0-9]/ // [^] means exclusion // Any character other than are = /[^a]/ // . Represents any character except line breaks. If you want to match, you need to escape /\./re = /./ // Other character sets //Arbitrary word characters [A-Za-z0-9_]re = /\w/ // Exclude word characters [^A-Za-z0-9_]re = /\W/ // Any number [0-9]re = /\d/ // Exclude numbers [^0-9]re = /\D/ // Spacere = /\s/ // Exclude spacesre = /\S/ // Word boundariesre = /\b/ // Exclude word boundariesre = /\B/ // Beginning and ending, ^ represents the beginning of the string, and $ represents the end of the string // Match the start position are = /^a/ // Match the end position are = /a$/ // Match subtitle a, exactly match, string and regular exactlyre = /^a$/
9.3 Quantitative Words
// 3 alet re = /a{3}/ // At least 3 are = /a{3,}/ // 3~6 are = /a{3,6/ // Multi-character matching: Two matches only take effect on one character in front of the quantifier. For example, /ab{3}/, it will only detect b, not ab. If you want to detect ab, you need to use ()re = /(ab){3}/ // Any lowercase letters at the beginningre = /^[a-z]{3}/ // + means more than one, equivalent to {1,}re = /a+/ // * means any numberre = /a*/ // ? means 0-1 time, equivalent to {0,1}re = /a?/
9.4 Expression matching pattern
1. Default (greedy mode)
- In JavaScript regular expressions, by default quantifiers (e.g.
*
、+
、?
) is greedy. This means they will match as many characters as possible. - For example, for regular expressions
/a.*b/
and strings"aabbbc"
, it will match from the first onea
To the last oneb
the entire string, i.e."aabbbc"
. because.*
Will match as many characters as possible until the last one is encounteredb
。
2. Non-greedy mode (lazy mode)
- By adding after the quantifier
?
It can be converted to non-greedy mode. In non-greedy mode, quantifiers match as few characters as possible. - For example, for regular expressions
/a.*?b/
and strings"aabbbc"
, it will match"aab"
. because.*?
Will meet the first oneb
When the match is stopped, only the fewest characters are matched to satisfy the expression.
3. Global matching pattern (g
)
- When added at the end of the regular expression
g
Logo (such as/pattern/g
) it does a global match. This means that all matching parts are looked up throughout the string, rather than just finding the first match and stopping. - For example, for regular expressions
/a/g
and strings"aaab"
, it will match alla
, return one containing threea
array (in usematch
when the method). If notg
The flag will only return to the first onea
。
4. Case-insensitive matching pattern (i
)
- Add at the end of the regular expression
i
Logo (such as/pattern/i
) will make the match case insensitive. - For example, for regular expressions
/a/i
and strings"Aa"
, it will matchA
, because it is case-insensitive.
5. Multi-line matching pattern (m
)
- When added
m
Logo (such as/pattern/m
)hour,^
and$
The matching behavior changes.^
It can not only match the beginning of a string, but also the beginning of each line;$
It can not only match the end of a string, but also the end of each line. - For example, for regular expressions
/^a/m
and strings"a\nb"
, it will match the beginning of the first linea
, if notm
flag, it will only match the beginning of the entire stringa
, this example will not match
9.5 Regular Expression Extraction
exec() is used to get the contents of the string that conform to regular expressions.
let str = "abc123bcc456cbdd" let re = /\d+/ig // '123' is the result of this match. Index is the matching string. The starting index position of the string in the original input string is 3. The input is the original string. The group is the group.((str)) // [ '123', index: 3, input: 'abc123bcc456cbdd', groups: undefined ] ((str)) // [ '456', index: 9, input: 'abc123bcc456cbdd', groups: undefined ] // Each time it is called, it will only match once, and multiple calls will match backwards one after another. For null, it means that the match is over and there is no match.((str)) // null // Use() to group str = "abcadcacc" // Match a*c, use() to group the middle charactersre = /a([a-z])c/ // abc is the content matched this time, b is the content in the group((str)) // [ 'abc', 'b', index: 0, input: 'abcadcacc', groups: undefined ]
9.6 Regular method for strings
let str = "llaacqqabcccaccdd" // A string can be split according to regular expressions ((/a[a-z]c/)) // [ 'll', 'qq', 'cc', 'dd' ] // Replace the specified content in the string according to the regular expression((/a[a-z]c/g,"@")) // ll@qq@cc@dd // You can search for the first time the content that conforms to the regular expression appears in the string((/a[a-z]c/)) // 2 // Match all contents in the string according to the regular expression((/a/g)) // [ 'a', 'a', 'a', 'a' ] // Match the content in the string that meets the requirements according to the regular expression (g global matching must be set), and the return is an iterator((/a/g)) // Object [RegExp String Iterator] {}
10. Garbage recycling mechanism
- If an object does not have any variables to reference it, then this object is a garbage object
- The existence of garbage objects will seriously affect the performance of the program.
- There is an automatic garbage collection mechanism in JS. These garbage objects will be automatically recycled by the interpreter, and we do not need to manually process them.
- The only thing we can do for garbage collection is to set variables that are no longer used to null
let obj = { value: 1 }; let anotherObj = obj; // The number of references of obj is increased to 2obj = null; // The number of references of obj is reduced to 1anotherObj = null; // The number of references of obj is reduced to 0 and can be recycled by the garbage collector
The above is a detailed explanation of the built-in objects in JavaScript. For more information about built-in objects in JavaScript, please pay attention to my other related articles!