Original and reference values
Raw value — the simplest data;
Reference value – An object made up of multiple values. Objects in JS are reference values.
1. Storage location
- The original value is fixed in size and stored in stack memory.
- Reference values are objects stored in heap memory.
2. Access mode
- The variable that holds the original value is accessed by value,
- A reference value is an object stored in memory. JavaScript doesn’t allow direct access to memory locations, and when you manipulate an object, you’re actually manipulating a reference to the object, not the actual object itself. Thus, variables holding reference values are accessed by reference.
Dynamic properties
For reference values, attributes and methods can be added, modified, and removed at any time.
The original value cannot have attributes, although attempts to add attributes to the original value do not generate an error.
Let person = new Object(); person.name = "Leo"; console.log(person.name); //"Leo" 2. Let name = "Mary"; name.age = 20; console.log(name.age); //undefinedCopy the code
If you use the new keyword, JavaScript creates an instance of type Object.
let name2 = new String("Lili");
name2.age = 18;
console.log(name2.age); //18
console.log(typeof name2); //object
Copy the code
Duplicate values
- The original value
Both num1 and num2 store values of 5, but the two variables can be used independently and do not interfere with each other. The value of num2 is a copy of the value of num1.
let num1 = 5; let num2 = num1; console.log(num1+" "+num2); //5 5 num1+=1; num2+=2; console.log(num1+"..." +num2); / / 6... 7Copy the code
- Reference value
The value copied here is actually a pointer to an object stored in heap memory, and the two variables actually point to the same object.
let obj1 = new Object();
let obj2 = obj1;
obj1.name = "Mary";
console.log(obj2.name); //"Mary"
Copy the code
Passing parameters
Arguments to all functions in ECMAScript are passed by value and are local variables.
When obj is overridden inside a function, it becomes a pointer to a local object. The local object is destroyed at the end of the function execution.
function setName(obj){
obj.name = "Jack";
obj = new Object();
obj.name = "Anny";
}
let person = new Object();
setName(person);
console.log(person.name); //Jack
Copy the code
Determine the type
The instanceof operator
The instanceof operator returns true if the variable is an instanceof the given reference type.
All reference values are instances of Object, so detecting any reference values and Object constructors with the instanceof operator returns true.
console.log(person instanceof Object); // Is the variable person Object? trueCopy the code
If instanceof is used to detect the original value, false is always returned because the original value is not an object. The original values should use the typeof operator mentioned earlier.
Execution context and scope
Execution context
Execution contexts are divided into global, function, and block-level contexts.
The context of variables or functions determines what data they can access and how they behave.
Each context has an associated object that holds all variables and functions defined by the context.
- The context is destroyed after all of its code has been executed. The global context is not destroyed until the application exits, such as closing the web page or exiting the browser.
- When code in the context executes, it creates a chain of scope objects for variables. The variable objects in the context in which the code is executing are always at the top of the chain. The variable object of the global context is always the last variable object in the scope chain.
- The connections between contexts are linear and ordered. Each context can search variables and functions in the upper-level context, but no context can search in the lower-level context.
Global context
Is the outermost context. In browsers, the global context is the Window object, and all global variables and functions defined by var are called properties and methods of the Window object.
Top-level declarations using lets and const are not defined in the global context, but have the same effect on scoping resolution.
Function context
Each function call has its own context, and the execution flow of an ECMAScript program is controlled by the context stack
The scope chain is enhanced
When the code executes in any of the following cases, a temporary context is added to the front of the scope chain, which is removed after the code executes.
- The catch block of a try/catch statement
- With statement
The with statement adds the specified object to the front of the scope chain;
The catch statement creates a new variable containing the declaration of the error object to be thrown.
The garbage collection
JavaScript implements memory allocation and idle resource reclamation through automatic memory management.
The basic idea: Determine which variable will no longer be used, and then release the memory it occupies. That is, the garbage collection program will run automatically at regular intervals, with a periodicity.
Values that leave scope are automatically marked as recyclable and then deleted during garbage collection.
Garbage collection strategy:
1. Mark cleaning
That is, values that are not currently in use are tagged and then returned to reclaim their memory.
Variables are marked as they pass in and out of context.
2. Reference count
For each value, the number of times it is referenced is recorded.
The next time the garbage collector runs, it frees memory that references the value of book 0.
Problems arise when there are circular references in your code.
Memory management
Dereference [properties suitable for global variables and objects]
If the data is no longer necessary, set it to NULL, freeing its reference.
Properties suitable for global variables and global objects. Local variables are automatically dereferenced when they go out of scope.
Dereferencing a value does not automatically cause the associated memory to be reclaimed.
The key to de-referencing is to ensure that the associated value is no longer in context, so it will be collected in the next garbage collection.
Dereferencing variables not only eliminates circular references, but also helps with garbage collection.
Basic reference types
A reference value (or object) is an instance of a particular reference type. A function is also a reference type.
A reference type is a structure that organizes data and functionality together, sometimes called an object definition, describing the properties and methods that an object should have.
Date
parse()
Takes a string argument representing a date, converting the string to the number of milliseconds for that date. The string format is as follows:
UTC()
The receiving parameters are year, number of zero-starting months (0 is January, 1 is February…….) , day (1-31 days), hour (0-23 days), minute, second, and millisecond. Year and month are required.
now()
Returns the number of milliseconds that represent the date and time when the method was executed.
Method of inheritance
- ToLocaleString () returns the date and time consistent with the local environment in which the browser is running, but does not contain time zone information.
- ToString () usually returns the date and time with the time zone information in the 24-hour system (0 to 23).
- ValueOf () does not return a string at all. Instead, it returns a millisecond representation of the date, and operators such as < and > can use the value it returns directly.
RegExp
The RegExp object represents a regular expression and is typically used to retrieve text that contains a specified string.
let expression = /pattern/flags;
- Pattern – A string used to specify the matching rules of regular expressions or fill in other regular expressions.
- Flags-matching mode, which is optional.
The matching mode is as follows:
All the metacharacters using backslash to escape in the model, yuan characters include ([]} {\ ^ $|)? * +.
Matches the first “[BC]at”, ignoring case
let pattern2 = /[bc]at/i
// Literal // Match the first "bat" or "cat", ignore case let pattern1 = /[BC]at/ I; // Constructor // same as pattern1, but let pattern2 = new RegExp("[BC]at"," I ") created with the constructor;Copy the code
Note that the two arguments in the constructor are strings.
Instance methods
1. 【 primary 】
Only one parameter is accepted, the string to be matched. Attributes: index- initial index of the matching pattern, input- string of queries.
2. test()
Used to test a specific sequence of values, often to validate user input.
3. ToLocaleString () and toString ()
Gets the form of a regular expression literal.
let str = 'abcabce'; let pattern = /(.) b(.) /g; let result = pattern.exec(str); console.log(result.input); // Abcabce query string console.log(result.index) //0 Match mode start subscript console.log(result[0]); // ABC matches the string console.log(result[1]); //a matches the string console.log(result[2]) for the first capture group in STR; //c matches the string of the second capture group in STRCopy the code
Note: The valueOf() method of a regular expression returns the regular expression itself.
Property of the RegExp constructor
let text = 'this is a sentence'; let pattern = new RegExp("(.) s","g"); if(pattern.test(text)){ console.log(RegExp.input); // this is a sentence console.log(RegExp.lastMatch); // is the last matching text console.log(regexp.lastparen); // I last matched capture group console.log(regexp.leftContext); // th console.log(RegExp.rightContext); // is a sentence }Copy the code
Get a capture group of up to nine matches, RegExp.$1 to RegExp.$9 to access the matches.
Short: RegExp[” $_ “]
Note: None of the properties of the RegExp constructor have any Web standard provenance, so do not use them in a production environment.
A function is an object
One of the more unique aspects of JS is that functions are actually instances of type Function, i.e. functions are also objects, so functions also have methods.
Raw value wrapper type
To facilitate manipulation of raw values, ECMAScript provides three special reference types: Boolean, Number, and String,
These types have the same characteristics as other reference types and have special behaviors corresponding to their respective primitive types. Every time a method or property with a primitive value is used, an object of the corresponding primitive wrapper type is created in the background.
The main difference between reference types and raw value wrapper types is the life cycle of the object. After a reference type is instantiated with new, the resulting instance is destroyed when it leaves scope, and the automatically created raw value wrapper object only exists for the execution of the line of code that accessed it.
let s1 = "some text"; // let s1 = new String("some text"); Create an instance of String s1.color = "red"; console.log(s1.color); // undefinedCopy the code
The Object constructor, as a factory method, returns an instance of the corresponding primitive value wrapper type based on the type of the value passed in.
Note that calling a primitive value wrapper type constructor with new is not the same as calling a transformation function of the same name.
let value = "25"; let number = Number(value); // Console. log(typeof number); // "number" let obj = new Number(value); // Constructor console.log(typeof obj); // "Object"Copy the code
Common characteristics
- Each wrapper type maps to a primitive type of the same name;
- When raw values are accessed in read mode, the background instantiates a raw value wrapper object through which data can be manipulated.
- The wrapped object is destroyed as soon as the statement involving the original value is executed.
4. Boolean Used less often
Is the reference type corresponding to a Boolean value. To create a Boolean object, use the Boolean constructor and pass in true or false.
The difference between a primitive value and a reference value (Boolean object) :
1) The typeof operator returns “object” for reference values, while the original value is “Boolean”.
2) Boolean objects are instances of Boolean types. The instanceof operator returns true and the original value false.
Number
Is the reference type of the corresponding numeric value. Directly instantiating the Number object is not recommended.
The toString() method optionally takes an argument representing the cardinality and returns a numeric string in the form of the corresponding cardinality.
let num = 10;
console.log(num.toString()); // "10"
console.log(num.toString(2)); // "1010"
console.log(num.toString(8)); // "12"
console.log(num.toString(16)); // "a"
Copy the code
ToFixed (x) method
Returns a numeric string containing only the number of decimal places. The x argument indicates that the numeric string returned contains x decimal places. If the decimal of the value itself is greater than the parameter X, it is rounded to the nearest significant bit.
Let num = 10.005; console.log(num.toFixed(2)); / / "10.01"Copy the code
ToExponential (y) [value that can represent a value of 1~21 decimal places]
Returns a numeric string in scientific notation. The y parameter represents the number of small numbers in the result.
let num = 10; cosole.log(num.toExponential(1)); 1.0 e+1 "/ /"Copy the code
toPrecision( z )
Returns the most reasonable output, depending on the situation, either in the form of fixed length or scientific notation. The parameter Z represents the total number of digits (excluding the exponent) in the result.
let num = 99; console.log(num.toPrecision(1)); // "1e+2" is 100, because 99 is not a 1-digit number, it can only be rounded to 100.console. log(num.toprecision (3)); / / "99.0"Copy the code
isInteger()
Used to tell if a value is saved as an integer, but sometimes the decimal digit 0 May be mistaken for a floating point value.
isSafeInteger()
Use to identify whether an integer is within the range of the safe integer.
A safe integer ranging from -2^53+1 to 2^53-1. Values beyond this range may be represented as a completely different binary value, even if an attempt is made to save them as integers.
String
Is the reference type of the corresponding string. Each String object has a length attribute that represents the number of characters in the String. Note that even if the string contains double-byte characters (rather than single-byte ASCII characters), it is still counted as single-character.
JavaScript character
Each 16-bit code corresponds to one character. That is, the length property of the string indicates how many 16-bit codes the string contains. JavaScript strings use a strategy that mixes two Unicode encodings: UCS-2 and UTF-16.
CharAt (x) returns the character of the given index position x.
CharCodeAt () checks the character encoding of the specified symbol and returns the value of the symbol at the specified index position, which is specified as an integer.
FormCharCode () is used to create characters in a string based on a given UTF-16 code element, can take any number of numeric values, and returns a string that concatenates the corresponding characters of all numeric values.
Each character is represented by 16 bits, and 16 bits can only uniquely represent 65536 characters, which is sufficient for most language character sets and is called the Basic Multilingual plane (BMP) in Unicode. To represent more characters, Unicode adopts a strategy of selecting a supplementary plane using an additional 16 bits per character, and using two 16 bits per character, called a proxy pair.
To properly parse strings that contain both singletons and proxy pairs, codePointAt () can be used instead of charCodeAt (), which takes the index of the 16-bit code element and returns the codePointAt that index position, which is the complete identification of a character in Unicode. The code point may be 16 bits /32 bits. FormCharCode () also has a formCodePoint (), which takes any number of code points and returns a concatenated string of the corresponding characters.
The normalize ()
To apply the normalized form to a string, you need to pass in a string representing what form: “NFD”, “NFC”, “NFKD”, or “NFKC”.
String manipulation methods
1. The concat ()
Concatenate one or more strings into a new string. The plus operator (+) is more convenient for concatenating multiple strings.
2. Method of extracting substrings
Slice (), substr (), and substring () each take one or two arguments, the first indicating where the substring begins and the second indicating where the substring ends.
For slice () and substring (), the second argument is where the extraction ends (that is, any characters preceding that position are extracted);
For substr (), the second argument represents the number of substrings returned. In any case, omitting the second argument extracts to the end of the string by default.
let info = "hello cln1003"; The console. The log (info. Slice (3, 7)); / / "lo cl" console log (info. The substr (3, 7)); / / "lo cl" console log (info. The substring (3, 7)); // "lo cln1"Copy the code
When an argument is negative, slice () treats all negative arguments as string length plus negative argument values; Substr () takes the first negative argument as the length of the string plus the value, and converts the second negative argument to 0; Substring () converts all negative argument values to 0.
let info = "hello cln1003"; console.log(info.slice(3,-4)); / / lo "herculean task" slice (3, 9 + (4) 】 【 13) console. The log (info. The substr (3, 4)); // "(empty string) because this is substr (3,0). console.log(info.substring(3,-4)); // "hel" because substring(3,0) is equivalent to substring(0,3), take smaller arguments as the starting point and larger arguments as the ending point.Copy the code
String position method
IndexOf ()
IndexOf () looks for substrings starting at the beginning of the string.
The lastIndexOf ()
The lastIndexOf () method looks for substrings starting at the end of the string.
Can accept an optional second parameter indicating where to start the search. If not found, -1 is returned.
String inclusion method
ES6 adds three new methods for determining whether a string contains another string, returning a Boolean value indicating whether it contains another string.
StartsWith ()
StartsWith () checks for matches starting at index 0.
EndsWith ()
EndsWith () checks matches starting at index (string.length-substring.length). The second optional argument represents the position that should be taken as the end of the string.
Includes ().
Includes () checks the entire string. The second optional parameter to the startsWith () and includes () methods, indicating where to start the search.
let msg = "foobarbaz";
console.log(msg.startsWith("foo")); // true
console.log(msg.startsWith("foo", 1)); // false
console.log(msg.includes("bar")); // true
console.log(msg.includes("bar", 4)); // false
console.log(msg.endsWith("bar")); // false
console.log(msg.endsWith("bar", 6)); // true
Copy the code
The trim () method
Creates a copy of the string, removes all preceding and following Spaces, and returns the result. Returns a copy of the string. The original string is not affected. The trimLeft () and trimRight () methods are used to clean up Spaces from the beginning and end of the string, respectively.
Repeat () method
Takes an integer argument indicating how many times the string is copied, and then returns the result of concatenating all copies.
PadStart () and padEnd() methods
Copies the string, if less than the specified length, padding characters on the corresponding side until the length condition is met. The first argument is length, and the second argument is an optional padding string, which defaults to a space.
The optional second argument is not limited to one character; if a string of more than one character is provided, it is truncated to match the specified length. If the length is less than or equal to the string length, the original string is returned.
let string = "cln";
console.log(string.padStart(8, "cute")); // "cuteccln"
console.log(stirng.padStart(2)); // "cln"
console.log(string.padEnd(8, "cute")); // "clncutec"
console.log(stirng.padEnd(2)); // "cln"
Copy the code
String case conversion
ToLowerCase (), toLocaleLowerCase(), toUpperCase() and toLocaleUpperCase(). ToLocaleLowerCase () and toLocaleUpperCase() are locale-specific implementations. It is best to use a locale-specific conversion method.
String pattern matching method
Match ()
Essentially the same exec () method as the RegExp object. Accepts a parameter, either a regular expression string or a RegExp object.
The array returned is the same as that returned by the exec () method of the RegExp object: the first element is a string that matches the entire pattern, and the remaining elements are strings that match the capture group in the expression, if any.
Search ()
The only argument accepted is the same as the match () method, which always matches the pattern backwards from the beginning of the string, returning the index of the position of the first match of the pattern, or -1 if none is found.
The split ()
Splits the string into arrays based on the delimiter passed in. The delimiter argument can be a string or a RegExp object, and the optional second argument is the array size, ensuring that the array returned does not exceed the specified size.
let colors = "red,blue,green,yellow"; let color1 = colors.split(","); // ["red","blue","green","yellow"] let color2 = colors.split(",", 2); // ["red", "blue"] let color3 = colors.split(/[^,]+/); // ["", ",", ",", ",", "]Copy the code
The third call, using a regular expression, returns an array that contains a comma and returns two empty strings before and after the regular expression because the delimiter appears at the beginning of the string (” red “) and at the end (” yellow “).
LocaleCompare ()
Comparing two strings returns three types of values:
(1) If alphabetically the string should precede the string arguments, return a negative value (usually -1);
(2) Return 0 if the string is equal to the string argument;
(3) Return a positive value (usually 1) if the string should be alphabetically placed after the string arguments;
let str = "yellow";
console.log(str.localeCompare("brick")); // 1
console.log(str.localeCompare("yellow")); // 0
console.log(str.localeCompare("zoo")); // -1
Copy the code
Substring substitution methods
To simplify substring replacement operations, ES provides the replace () method that takes two arguments, the first of which can be a RegExp object or a string (which is not converted to a regular expression), and the second can be a string or a function. If argument 1 is a string, only the first substring is replaced; To replace all substrings, parameter 1 must be a regular expression with a global tag.
let text = "cat, bat, sat";
let result = text.replace("at","ond");
console.log(result); // "cond, bat, sat"
result = text.replace(/at/g, "ond");
console.log(result); // "cond, bond, sond"
Copy the code
Singleton built-in object
A built-in object is defined as “any object provided by an ECMAScript implementation, independent of the host environment, and existing at the beginning of execution of an ECMAScript program.” We’ve touched on most of the built-in objects, such as Object, Array, and String.
Global
Variables and functions defined in the Global scope become properties of the Global object. IsNaN (), isFinite(), parseInt(), and parseFloat(), described earlier, are actually methods of Global objects.
1.URL encoding method
EncodeURI () and encodeURIComponent () are used to encode the Uniform resource representation (URI) for passing to the browser. Valid URIs cannot contain certain characters, such as Spaces, and you can use URI encoding methods to make them understandable to the browser.
EncodeURI ()
Used to encode the entire URI, such as “www.baidu.com/login.js”, without encoding special characters belonging to URI components, such as colons, slashes, question marks, and hAshes.
EncodeURIComponent ()
Use to encode individual components of urIs, such as “login.js” in the previous URL. It encodes any nonstandard characters it finds. Higher frequency of use.
let uri = "http://www.baidu.com/user login.js#start";
// "http://www.baidu.com/user%20login.js#start"
console.log(encodeURI(uri));
// "http%3A%2F%2Fwww.baidu.com%2Fuser%20login.js%23start"
console.log(encodeURIComponent(uri));
Copy the code
The corresponding decoding method is decodeURI () and decodeURIComponent (), which can only decode the corresponding encoded characters.
2. The eval() method [be used with extreme caution]
Is a complete ECMASript interpreter that takes a single argument, an ECMASript (JavaScript) string to execute.
eval("console.log('hi')"); Equivalent to the console. The log (" hi ");Copy the code
You can define a function or variable inside eval() and reference it in external code.
eval("function sayHi() { console.log('hi'); } "); sayHi();Copy the code
In strict mode, variables and functions created inside Eval () cannot be accessed externally, and assigning to eval causes errors.
3. Global object properties
The previously mentioned special values such as undefined, NAN, and Infinity are properties of the Global object. In addition, all native reference type constructors, such as Object and Function, are also properties of the Global Object.
4. The window object
The browser implements the Window object as a proxy for the Global object, so all variables and functions declared in the Global scope become properties of the window.
Calling a function that simply returns this is a common way to get a Global object in any execution context.
let global = function () {
return this;
} ();
Copy the code
Math
1. Math object properties
2. Min () and Max () methods
Used to determine maximum and minimum values in a set of values, eliminating the need for additional loops and if statements to determine maximum/minimum values.
3. Rounding method
- The math.ceil () method always rounds up to the nearest integer;
- The math.floor () method always rounds down to the nearest integer;
- Math.round () performs rounding;
- The math.fround () method returns the closest single-precision (32-bit) floating-point representation of the value.
4. Random () method
Returns a random number in the range 0-1 that contains 0 but not 1.
If need to generate a random number for encryption, recommend the use of the window. The crypto. GetRandomValues ().