Basic reference type
A reference value (object) is an instance of a particular reference type. In ECMAScript, reference types (sometimes referred to as object definitions) are structures that organize data and functions together.
Object is considered an instance of a specific reference type. The new object is created by using the new operator followed by a constructor.
1, date
The Date type saves the Date as the number of milliseconds that have elapsed since midnight (0:00) coordinated universal time (UTC) on January 1, 1970.
The code is as follows (example):
let now=new Date();
Without passing parameters to the Date constructor, the created object will save the current Date and time. To create a Date object based on another Date and time, you must pass in its millisecond representation. ECMAScript provides two auxiliary methods for this: Date.parse() and Date.UTC().
The Date.parse() method receives a string parameter representing the date. If the string passed to Date.parse() does not represent a date, NaN is returned. Supported formats:
- "Month / day / year", such as "May 23 / 2019"
- "Month name, day, year", such as "May 23, 2019"
- "Week day month name day year hour: minute: second time zone", such as "Tue May 23 2019 00:00:00 GMT-0700"
- ISO 8601 extended format "YYYY-MM-DDTHH:mm:ss:sssZ", such as "2019-05-23T00:00:00"
The code is as follows (example):
let someDate=new Date(Date.parse("May 23, 2019"));
The Date.UTC() method also returns the millisecond representation of the date and passes it to the Date.UTC() parameter
Are year, zero starting month, day, hour, minute, second, and millisecond. Only the month and year are required.
The code is as follows (example):
let allFives=new Date(Date.UTC(2000,4,5,17,55,55)); //GTM time: 5:55:55 p.m. on May 5, 2000
ECMAScript also provides a Date.now() method, which returns the number of milliseconds representing the date and time when the method is executed.
1. Inheritance method
The toLocaleString() method of type Date returns a Date and time consistent with the local environment in which the browser is running. This means that the format contains AM (morning) and PM (afternoon) for time, but does not contain time zone information.
The toString() method of Date type usually returns the Date and time with time zone information, and the time is also expressed in 24-hour system (0 ~ 23).
The ValueOf() method of type Date does not return a string and returns the millisecond representation of the Date.
2. Date format
The Date type has several special ways to format dates. They will return strings:
- toDateString() displays the day of the week, month, day and year in the date
- toTimeString() displays the hour, minute, second, and time zone in the date
- toLocaleDateString() displays the day of the week, month, day and year in the date
- toLocaleTimeString() displays the hours, minutes, and seconds in the date
- toUTCString() displays the full UTC date
3. Date / time component method
2, RegExp
ECMAScript supports regular expressions through the RegExp type. Syntax:
let expression=/pattern/flags;
The pattern of a regular expression can be any simple or complex regular expression. Each regular expression can take zero or more flags.
Tag matching pattern:
- g: Global mode, which means to find all the contents in the string, rather than end when the first matching content is found.
- i: Case insensitive, which means that the case of pattern and string is ignored when finding a match.
- m: Multiline mode, which means that the search will continue when the end of a line of text is found.
- y: Glue mode, which means that only strings starting from and after lastIndex are found.
- u: Unicode mode, enabling Unicode matching.
- s: dotAll mode, representing metacharacters. Matches any character (including \ n or \ r).
Metacharacters have one or more special functions in regular expressions, so to match the above characters themselves, you must use a backslash (\) to escape.
Regular expressions can be created using the RegExp constructor, which takes two parameters: a pattern string and an (optional) tag string.
The code is as follows (example):
let pattern1=/[bc]at/i;//Literal formal definition let pattern2=new RegExp("[bc]at","i");//Constructor formal definition
1.RegExp instance properties
Each RegExp instance has the following properties:
- global: Boolean value indicating whether the g flag is set.
- ignoreCase: Boolean value indicating whether the i flag is set.
- unicode: Boolean value indicating whether the u flag is set.
- sticky: Boolean value, which indicates that the y value is set in both.
- lastIndex: an integer indicating the starting position of the next search in the source string, always starting from 0.
- multiline: Boolean value indicating whether the m flag is set.
- dotAll: Boolean value indicating whether the s flag is set.
- source: literal string of regular expression, without slashes at the beginning and end.
- flags: the tag string of the regular expression. Always return as a literal rather than a string pattern passed into the constructor.
The code is as follows (example):
let pattern=new RegExp("\\[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"
2.RegExp instance method
The main method of RegExp instance is exet(), which is mainly used in conjunction with the group. This method receives only one parameter, the string to which the pattern is to be applied. If a match is found, the Array containing the first match information is returned. If not, null is returned. Although the returned Array is an instance of Array, it contains two additional properties: index (the starting position of the matching pattern in the string) and input (the string to find).
The code is as follows (example):
let text ="mom and dad and baby"; let pattern=/mom( and dad( and baby)?)?)/gi; let matches=pattern.exec(text); console.log(matches.index);//0 console.log(matches.input);//"mom and dad and baby" console.log(matches[0]);//"mom and dad and baby" console.log(matches[1]);//" and dad and baby" console.log(matches[2]);//" and baby"
If the pattern has a global flag set, each call to the exec() method returns a matching message. If the g flag is set, each call to exec() searches the string for the next match.
The code is as follows (example):
let text ="cat, bat, sat, fat"; let pattern=/.at/; let matches=pattern.exec(text); console.log(matches.index);//0 console.log(matches[0]);//"cat" console.log(pattern.lastIndex);//0, lastIndex remains unchanged in non global mode let matches=pattern.exec(text); console.log(matches.index);//0 console.log(matches[0]);//"cat" console.log(pattern.lastIndex);//0
The code is as follows (example):
let text ="cat, bat, sat, fat"; let pattern=/.at/g;//Global proxy set let matches=pattern.exec(text); console.log(matches.index);//0 console.log(matches[0]);//"cat" console.log(pattern.lastIndex);//3 let matches=pattern.exec(text); console.log(matches.index);//5 console.log(matches[0]);//"bat" console.log(pattern.lastIndex);//8 let matches=pattern.exec(text); console.log(matches.index);//10 console.log(matches[0]);//"sat" console.log(pattern.lastIndex);//13
Another method of regular expressions is test(), which takes a string parameter. If the entered text matches the pattern, the parameter returns true; otherwise, it returns false. This method is applicable to the case where you only want to test whether the patterns match without actually matching the content.
No matter how the regular expression is created, the inherited methods toLocaleString() and toString() return the literal representation of the regular expression.
3.RegExp constructor property
RegExp constructor property
full name | Abbreviation | explain |
---|---|---|
input | $_ | Last searched string (nonstandard property) |
lastMatch | $& | Last matching text |
lastParen | $+ | Last matched capture group (non-standard attribute) |
leftContext | $` | The text that appears before lastMatch in the input string |
rightContext | $' | The text in the input string that appears after lastMatch |
The code is as follows (example):
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
4. Model limitations
Although ECMAScript has made great progress in supporting regular expressions, it still lacks some advanced features in the corresponding Perl language.
- \A and \ z anchors (match the beginning and end of the string, respectively)
- Joint and cross category
- Atomic group
- x (ignore spaces) matching pattern
- Conditional matching
- Regular expression annotation
3, Original value wrapper type
To facilitate the manipulation of raw values, ECMAScript provides special reference types in 3: Boolean, Number, and String. Whenever a method or property of an original value is used, an object of the corresponding original wrapper type will be created in the background, exposing various methods of operating the original value.
The code is as follows (example):
let s1="some text"; let s2=s1.substring(2);//Access s1 in read mode
Whenever accessing a String value in read mode, the following three steps will be performed in the background (String as an example):
- Create an instance of String type
- Calling a specific method on an instance
- Destroy instance
The code is as follows (example):
let s1=new String("some text"); let s2=s1.substring(2); s1=null;
The main difference between the reference type and the original value wrapper type is the life cycle of the object. After instantiating the reference type through new, the resulting instance will be destroyed when it leaves the scope, while the automatically created original value wrapper object only exists during the execution of the line of code accessing it.
The code is as follows (example):
let s1="some text"; s1.color="red"; console.log(s1.color);//undefined
Calling typeof on an instance of the original value wrapper type will return "object", and all original value wrapper objects will be converted to the Boolean value true.
As a factory method, the Object constructor can return an instance of the corresponding original value wrapper type according to the type of the incoming value. Note that calling the constructor of the original value wrapper type with new is different from calling the transformation function with the same name.
The code is as follows (example):
let obj=new Object("some text"); console.log(obj instanceof String);//true
The code is as follows (example):
let value="25"; let number=Number(value);//Transformation function console.log(typeof number);//"number" let obj=new Number(value);//Constructor console.log(typeof obj);//"object"
1.Boolean
Boolean is the reference type corresponding to the Boolean value. To create a Boolean object, use the Boolean constructor and pass in true or false.
The Boolean instance will override the valueOf() method and return an original value of true or false. The toString() method will also be overwritten when called, returning the string "true" or "false".
The code is as follows (example):
let falseObject=new Boolean(false); let result=falseObject&&true; //This expression is the value (true) of the false object object object, not its representation //All objects are automatically converted to true in Boolean expressions console.log(result);//true let falseValue=false; result=falseValue&&true; console.log(result);//false
2.Number
Number is the reference type of the corresponding value. To create a number object, use the number constructor and pass in a number.
The Number type overrides the valueOf(), toLocaleString(), and toString() methods. The valueof () method returns the original value represented by the Number object, and the other two methods return a numeric string. The toString () method optionally receives a parameter representing the cardinality and returns a string in the form of the corresponding cardinality.
The toFixed() method returns a numeric string containing the specified number of decimal places.
The code is as follows (example):
let num=10; cosole.log(num.toFixed(2));//"10.00"
The toExponential() method returns a numeric string in scientific notation.
The code is as follows (example):
let num=10; cosole.log(num.toExponential(1));//"1e+1"
The toPrecision() method will return the most reasonable output result according to the situation, which may be in the form of fixed length or scientific notation. This method receives a parameter representing the total number of digits (excluding exponent) in the result.
The code is as follows (example):
let num=99; cosole.log(num.toPrecision(1));//"1e+2" cosole.log(num.toPrecision(2));//"99" cosole.log(num.toPrecision(3));//"99.0"
isInteger() method and safe integer
ES6 adds the Number.isInteger() method to identify whether a value holds an integer.
The code is as follows (example):
console.log(Number.isInteger(1));//true console.log(Number.isInteger(1.01));//false
The IEEE754 numeric format has a special numeric range in which binary can represent an integer. This value ranges from Number.MIN_SAFE_INTEGER(-253 -1) to
Number.MAX_SAFE_INTEGER(253 -1).
To identify whether an integer is in this range, you can use the Number.isSafeInteger() method.
3.String
String is the reference type of the corresponding string. To create a string object, use the string constructor and pass in a value. The three inheritance methods of string valueOf(), toLocaleString() and toString() return the original string value of the object.
The code is as follows (example):
let stringObjec=new String("hello world");
JavaScript characters
A JavaScript string consists of 16 bit symbols. For most characters, each 16 bit symbol corresponds to one character. In other words, the length property of the string indicates how many 16 bit symbols the string contains.
The code is as follows (example):
let message="abcde"; console.log(message.length);//5
The charAt() method returns the character at the given index position, specified by the integer parameter passed to the method.
The code is as follows (example):
let message="abcde"; console.log(message.charAt(2));//"c"
The charCodeAt() method can view the character encoding of the specified symbol. This method returns the symbol value of the specified corresponding position.
The code is as follows (example):
let message="abcde"; console.log(message.charCodeAt(2));//99
The fromCharCode() method is used to create characters in a string based on a given UTF-16 symbol. This method can accept any number of values and return a string that concatenates the characters corresponding to all values.
The code is as follows (example):
console.log(String.fromCharCode(0x61,0x62,0x63,0x64,0x64));//abcde console.log(String.fromCharCode(97,98,99,100,101));//abcde
For characters in the range of U+0000~U+FFFF, the return results of these four methods are the same as expected, but this correspondence does not hold when extended to the Unicode supplementary character plane.
16 bits can only uniquely represent 65536 characters. In Unicode, it is called Basic Multilingual plane (BMP). In order to represent more characters, Unicode adopts a strategy that each character uses another 16 bits to select a supplementary plane. This strategy of using two 16 bit symbols per character is called proxy pair.
codePointAt() receives the index of a 16 bit code and returns the code point at the index position. The code point is the complete identification of a character in Unicode.
normalize() method
normalize() provides four normalized forms, including NFD, NFC, NFKD and NFKC, which can normalize characters similar to the above into a consistent format.
String operation method
The concat() method is used to splice one or more strings into a new string.
The code is as follows (example):
let stringValue="hello "; let result=stringValue.concat("world"); console.log(result);//hello world console.log(stringValue);//hello
ECMAScript provides three methods to extract substrings from strings: slice(), substr(), and substring(). These three methods all return the first substring of the string calling them, and they all receive one or two parameters. The first parameter represents the beginning of the character string, and the second parameter represents the end of the substring. For slice() and substring() For substr(), the second parameter is the position where the extraction ends (that is, the string before this position will be extracted). For substr(), the second parameter represents the number (length) of substrings returned. In any case, omitting the second parameter means extracting to the end of the character string.
The code is as follows (example):
let stringValue="hello world"; console.log(stringValue.slice(3));//"lo world" console.log(stringValue.substring(3));//"lo world" console.log(stringValue.substr(3));//"lo world" console.log(stringValue.slice(3,7));//"lo w" console.log(stringValue.substring(3,7));//"lo w" console.log(stringValue.substr(3,7));//"lo worl"
When a parameter is a negative value, slice() method treats all negative parameters as string length plus negative parameter value. sunstr() method treats the first negative parameter value as string length plus the value, and converts the second parameter value to 0. substring() method converts all negative parameter values to 0.
The code is as follows (example):
let stringValue="hello world";//11 console.log(stringValue.slice(-3));//"rld" console.log(stringValue.substring(-3));//"hello world" console.log(stringValue.substr(-3));//"rld" console.log(stringValue.slice(3,-4));//"lo w" console.log(stringValue.substring(3,-4));//"hel" console.log(stringValue.substr(3,-4));//""(empty)
String position method
There are two methods for locating substrings in a string: indexOf() and lastIndexOf(). These two methods search for the incoming string from the string and return the location (or - 1 if not found). The difference between the two is that the indexof () method looks for the substring from the beginning of the string, while the lastIndexOf () method looks for the substring from the end of the string.
The code is as follows (example):
let stringValue="hello world"; console.log(stringValue.indexOf("o"));//4 console.log(stringValue.lastIndexOf("o"));//7
String containing method
ECMAScript6 adds three methods to judge whether a string contains another string: startsWith(), endsWith(), and includes(). These methods search for the incoming string from the string and return a Boolean value indicating whether it is included.
The difference is that startsWidth() checks for matches starting at the 0 index, endsWith() checks for matches starting at the index (string.length-substring.length), and includes() checks for the entire string.
The code is as follows (example):
let message="foobarbaz"; console.log(message.startsWith("foo"));//true console.log(message.startsWith("bar"));//false console.log(message.endsWith("baz"));//true console.log(message.endsWith("bar"));//false console.log(message.includes("bar"));//true console.log(message.includes("qux"));//false
The startsWith() and include() methods receive an optional second parameter indicating where to start the search. The endsWith() method receives an optional second parameter indicating the position that should be taken as the end of the string. If this parameter is not provided, the default is the string length.
The code is as follows (example):
let message="foobarbaz"; console.log(message.startsWith("foo"));//true console.log(message.startsWith("foo",1));//false console.log(message.includes("bar"));//true console.log(message.includes("bar",4));//false console.log(message.endsWith("bar"));//false console.log(message.endsWith("bar",6));//true
trim() method
The trim() method creates a copy of the string, removes all the space characters before and after, and then returns the result.
The code is as follows (example):
let stringValue=" hello world "; let trimmedStringValue=stringValue.trim(); console.log(stringValue);//" hello world " console.log(trimmedStringValue);//"hello world"
The trimLeft() and trimlight () methods are used to clean up space characters from the beginning and end of a string, respectively.
repeat() method
The repeat() method receives an integer parameter indicating how many times to copy the string, and then returns the result after splicing all copies.
padStart() and padEnd() methods
The padStart() and padEnd() methods copy the string. If it is less than the specified length, fill in characters on the corresponding side until the length is met. The first parameter is length, and the second parameter is an optional fill string, which defaults to space.
The code is as follows (example):
let stringValue="foo"; console.log(stringValue.padStart(6));//" foo" console.log(stringValue.padStart(6,"."));//"...foo" console.log(stringValue.padEnd(6));//"foo " console.log(stringValue.padEnd(6,"."));//"foo..."
The optional second parameter is not limited to one character. If multiple character strings are provided, they are spliced and truncated to match the specified length. If the length is less than or equal to the string length, the original string is returned.
The code is as follows (example):
let stringValue="foo"; console.log(stringValue.padStart(2));//"foo" console.log(stringValue.padStart(8,"bar"));//"barbafoo" console.log(stringValue.padEnd(2));//"foo" console.log(stringValue.padEnd(8,"bar"));//"foobarba"
String iteration and Deconstruction
The string prototype exposes a @ @ iterator method that represents each method that can iterate over the string.
String case conversion
String case conversion includes: tolower case(), toLocaleLowerCase(), toUpperCase(), and toLocaleUpperCase(). The tolocalelovercase() and toLocaleUpperCase() methods are designed to be implemented on a locale specific basis.
String pattern matching method
The match() method is essentially the same as the exec() method of the RegExp object. The match() method receives a parameter, which can be a parameter, a regular expression string, or a RegExp object.
The only argument to the search() method is a regular expression string or RegExp object. This method returns the first matching location index of the pattern. If it is not found, it returns - 1.
The code is as follows (example):
let text="cat,bat,sat,fat"; let pos=text.search(/at/); console.log(pos);//1, that is, the position of the first character of "at" in the string
The replace() method receives two parameters. The first parameter can be a RegExp object or a string, and the second parameter can be a string or a function. If the first parameter is a string, only one substring will be replaced. To replace all substrings, the first parameter must be a regular expression with a global tag.
The code is as follows (example):
let text="cat,bat,sat,fat"; let result=text.replace("at","ond"); console.log(result);//"cond,bat,sat,fat" let result=text.replace(/at/g,"ond"); console.log(result);//"cond,bond,sond,fond"
The split() method splits the string into an array based on the delimiter passed in. The argument as a delimiter can be a string or a RegExp object. You can also pass in the second parameter, array size, to ensure that the returned array does not exceed the specified size.
The code is as follows (example):
let colorText="red,blue,green,yellow"; let color1=colorText.split(",");//["red","blue","green","yellow"] let color2=colorText.split(",",2);//["red","blue"] let color3=colorText.split(/[^,]+/);//["",",",",",",",""]
localeCompare() method
**The localeCompare() * * method compares consecutive strings. If the string should be in front of the string parameter in alphabetical order, it returns a negative value (usually - 1); If the string is equal to the string parameter, 0 is returned; Returns a positive value (usually 1) if the string should be at the end of the string parameter.
4, Single column built-in object
ECMA-262 defines the built-in object as "any object provided by the ECMAScript implementation, independent of the host environment, and existing at the beginning of the execution of the ECMAScript program".
1.Global
The Global object is the most special object in ECMAScript because code does not explicitly access it. ECMA-262 specifies that a Global object is a bottom-up object, which is aimed at attributes and methods that do not belong to any object. Variables and functions defined in the Global scope become properties of the Global object.
URL encoding method
The encodeURI() and encodeURIComponent() methods are used to encode a uniform resource identifier (URI) for transmission to the browser. The encodeURI() method encodes the entire URI, and the encodeURIComponent() method encodes individual components in the URI. The main difference between the two is that encodeURI() does not encode special characters that belong to the composition of the URL, such as colon, slash, question mark and pound sign, while encodeURIComponent() encodes all non-standard characters it finds.
The code is as follows (example):
let uri="http://www.wrox.com/illegal value.js#start"; //"http://www.wrox.com/illegal%20value.js#start" console.log(encodeURI(uri)); //"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start" console.log(encodeURIComponent(uri));
decodeURI() and decodeURIComponent() decode only characters encoded with encodeURI() and encodeURIComponent().
eval() method
The eval() method is a complete ECMAScript interpreter that receives a parameter, an ECMAScript string to execute.
The code is as follows (example):
eval("console.log('hi')");//hi console.log(eval('2 + 2'));//4
Global object properties
window object
The browser defines the window object as a proxy for the Global object. Therefore, all variables and functions declared in the Global scope become window properties.
The code is as follows (example):
var color="red"; function sayColor(){ console.log(window.color); } window.sayColor();//"red"
2.Math
ECMAScript provides math objects as a way to save mathematical formulas, information, and calculations. The Math object provides some properties and methods to assist in calculation.
Math object properties
min() and max() methods
The min() and max() methods are used to determine the minimum and maximum values in a set of values.
The code is as follows (example):
let max=Math.max(3,54,32,16); console.log(max);//54 let min=Math.min(3,54,32,16); console.log(min);//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. The Math.round() method performs rounding. The math. Forward() method returns the single precision (32-bit) floating-point value representation with the closest value.
random() method
The Math.random() method returns a random number in the range of 0 ~ 1, including 0 but not 1. Generate random number formula:
The code is as follows (example):
number=Math.floor(Math.random()*total_number_of_choices+first_possible_value)
Other methods
summary
Objects in JavaScript become reference values, and the built-in reference types in the set can be used to create specific types of objects.
reference values are similar to classes in traditional object-oriented programming languages, but the implementation is different.
the Date type provides information about the Date and time, including the current Date, time and related calculations.
RegExp type is ECMAScript's regular expression support interface, which provides most basic and some advanced regular expression functions.
The unique point of JavaScript is that functions are actually instances of Function type, that is, functions are also objects. Because functions are also objects, functions also have methods that can be used to enhance their capabilities.
Due to the existence of the original value wrapper type, the original value in JavaScript can be used as an object, with which the corresponding data can be manipulated. There are three primitive value wrapper types: Boolean, Number, and String. They all have the following characteristics:
each wrapper type maps to the original type with the same name.
when accessing the original value in read mode, an object of original value wrapping type will be instantiated in the background, with which the corresponding data can be operated.
after the statement involving the original value is executed, the wrapper object will be destroyed.
When the code starts executing, there are two built-in objects in the Global context: Global and math. The Global object is not directly accessible in most ECMAScript implementations. However, the browser implements it as a window object. All Global variables and functions are properties of the Global object. The Math object contains properties and methods that assist in complex calculations.