Reference type
A reference type is a data structure that organizes data and functionality together.
Reference type: Describes the properties and methods that a class of objects have, and an object is an instance of a particular reference type.
1.Object type
There are two ways to create an object instance:
(1) The new operator is followed by the object constructor
(2) Using object literal notation, the preferred way to pass a large number of optional parameters to the function; var person = {}
Object literal notation:
The property name of the object is automatically converted to a string;
Inside the function, you can use the TypeOf operator to detect the existence of each property;
Function Transfer technique: Use named arguments for mandatory values, and use object literals to encapsulate multiple optional parameters
Access Object properties: ① point notation: Person.name② Square bracket notation: person["name"]
(when square brackets are used, the properties to be accessed are placed in square brackets as strings or as variables)
2.Array type
Array: Each item can save any type of data, size can be dynamically adjusted;
Ways to create an array:
- var color = new Array () New can also be omitted;
- Literal notation: Do not follow a comma after the last item
When created with a constructor, you can pass to the constructor the containing item in the array, the length of the array (number), the containing item with multiple, separated by commas, and if a value is passed, the number is the specified length, and the other type of argument creates a value that contains that
Read and set the value of the array: use square brackets and provide an index, starting with 0
If the length of the array is set to a value greater than the number of items, each new item will get undefined;
The length property makes it easy to add a new item at the end of the array var co= [1,2,3,3];co[co.length]=4;co[co.length]=5;
- detecting arrays
The Array.isarray () method (IE9 and above) determines whether a value is an array, regardless of the global execution environment in which it was created, and instanceof is not a problem for a single global execution environment, but if there are multiple global execution environments, There will be a two version of the array constructor.
- Conversion method
ToString (): Returns a comma-delimited string of strings from each value in the array
ValueOf (): Returns or arrays,
toLocaleString (): Each item in the array is called toloaclestring, and then the comma is spliced,
Array items are returned by default as a comma-delimited string, and if you use the Join () method, you can specify the delimiter build string (only one argument, the delimiter string, and the default comma delimiter if not passed). If an item in the array is null or undefined, an empty string is returned
- Stack method (LIFO method)
Push (): You can receive any number of parameters, add them to the end of the array one by one, and return the modified numeric length; the Pop () method removes the last item from the end of the array, reduces the length of the array, and returns the removed item
- Queue Method (FIFO)
Shift () Moves the first item of the divisor group and returns the item, minus one for the array length, unshift () adds any item to the front of the array, and returns the new array length;
- Reorder Methods
Reverse (): Reverses the order of the array items, but is not flexible enough; if you just want to reverse the original order of the array, use this faster;
Sort (): Array items are sorted in ascending order by default (call the ToString method of each array item, get the string, and then determine how to sort, by default it causes the number 5 after 10, because the comparison is a string);
The sort method can receive a comparison function as a parameter, the comparison function receives two parameters, the return result is positive or negative 0;
- Operation Method (Value)
Concat () Method: does not change the original array, will return a newly constructed array;
The slice () method, which creates a new array based on one or more items of the current value, can receive one or two parameters (the start and end position of the item), only one ending position is the end of the array, and two returns the entry at the start and end position, but not the entry at the end position, without affecting the original value; If there are negative numbers, the array length plus the number determines the corresponding position, and if the end is less than the initial, an empty array is returned
Splice () method to insert an item into the middle of the array,
- Delete any number of items, the location of the first item to delete, and the number of items to delete
- Insert: Insert any item to the specified location, provide three parameters: Start position, 0 (number of items to delete) and items to insert, if you want to insert multiple items, you can pass in four, five, and any number of
- Replace: The parameter is: Start position, number of items to be deleted, and any item to insert, the number of items inserted does not have to be equal to the number of items deleted
Splice always returns an array that contains the deleted items from the original values (an empty array is returned if deleted as 0)
- Location method
IndexOf (), LastIndexOf () method, receives two parameters: the starting position of the item to find and (optional) lookup;
IndexOf (search backwards from 0);
LastIndexOf (looking forward from the end of the value)
Returns the position of the found item in the array, no case returns-1; equality operator (two objects, even if field names, values are the same, are not equal when the comparison is equal)
- Iterative methods
5 iterations of the method. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this; the function that passes in these methods receives three parameters: the value of the array item, the position of the item in the array, and the group object itself.
- Every each item in the array runs the given function, and returns TRUE if each item returns true
- The filter () runs the given function for each item in the array, and returns a list of the items that the function returns True
- ForEach () runs the given function for each item of the array. No return value
- Map () runs the given function for each item in the array. Returns an array of the results of each function call
- Some () runs the given function for each item of the array. Returns True if the function returns true for either item
None of the above methods will modify the included values in the function
- Narrowing method
Reduce (), reduceright (), both of which iterate over all items of the algebraic value, and then build a value that is ultimately returned
Reduce starts with the first entry, traversing through to the last
Reduceright starts from the last item and traverses forward
The receive parameters are: a function for each call and (optional) as the initial value for shrinking the base
The functions passed to reduce and reduceright receive 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument
3. Date type
Create Date Object: constructor new Date ()
You can create a Date object based on a specific date and time, you must pass in the number of milliseconds for that date, you can use Date.parse () and DATE.UTC (), the date object behaves differently in different browsers, and if 1 32,2007 some will parse to 2 1,2007, But some will parse into the current time.
- where the parse () method receives a string parameter that represents a date, and then attempts to return the corresponding number of milliseconds for the date based on that string. If the passed-in string cannot represent a date, Nan is returned. In fact, if the string is passed directly to the new Date (), Date.parse () is also called in the background;
- DATE.UTC () also returns the number of milliseconds that represent the date, the entry parameter is the year, the month (0-11), the number of days (1-31), The Hour (0-23), the minute, the second, and the milliseconds. Only the years are necessary, no days are 1, others are not 0;
The Date () constructor is the same as the DATE.UTC () receive parameter
The Date.now () method, which returns the milliseconds of the date and time when this method was called, is the same effect as using the + operator to convert the Ate object to a string in a browser that does not support it
- Methods of inheritance
Like other reference types, the date type overrides the toLocaleString (), toString (), and valueof () methods, where valueof returns the number of milliseconds and the other two return strings ; Date types can be compared using comparison operators (using valueof to convert to milliseconds)
- Method of date formatting
toDateString ()--display weekday, month, day, and year in an implementation-specific format
toTimeString ()--displays hours, minutes, seconds, and time zones in an implementation-specific format
toLocaleDateString ()--display weekday, month, day, and year in a locale-specific format
toUTCString ()--full UTC date in implementation-specific format
- Date, Event component method
- RegExp type
Each regular expression can have one or more flags (flags) that indicate the behavior of the regular expression, with the following three flags: G (global mode, applied with all strings), I (case-insensitive), M (multiline mode, which continues to find the next line at the end of a line)
The regular expression is a combination of a pattern and the above-mentioned symbol;
The meta-characters of regular expressions include (| { \ ^ $ | ? * + . [ ] }
The metacharacters used in the pattern must be escaped (that is, to match the metacharacters, with \)
Defining Regular Expressions
- Literal form: var pattern =/[bc]at/i
- Using the RegExp constructor, you receive two parameters, one is the string pattern to match, and the other is an optional flag string. var pattern1 = new RegExp ("[Bc]at", "I"), double escaping of characters in the constructor
ECMAScript 3, each regular expression literal always shares a regexp instance, and each new RegExp instance created with the constructor is a new instance; for the literal, the first call to test will find the cat, and the second will start at the end of the last match. After that, the next call to test begins at the beginning because it is at the end of the string.
- var re =null,
- I
- for (i = 0;i < 10;i++) {
- re =/cat/g;
- Re.test ("catastrophe");
- }
- for (i = 0;i < i++) {
- Re = Newregexp ("Cat", "G");
- Re.test ("catastrophe");
}
ECMAScript 5 explicitly stipulates that, like the constructor, a new RegExp instance is created each time
RegExp Instance Properties
RegExp instance local domain following properties
-Global Boolean value, whether the G flag is set
-IgnoreCase Boolean value, whether the G flag is set
-Multiline Boolean value, whether the M flag is set
-an LastIndex integer that represents the character position at which to start searching for the next occurrence, starting from 0
-The string representation of the source regular expression, returned in literal form rather than in the string pattern passed into the constructor
RegExp instance Method
EXEC (), the method is designed specifically for capturing groups;
EXEC () takes a parameter, which is the string to which the pattern is to be applied, and returns an array containing the first match information; returns null if no match is found
Returns the numeric value when the array instance, also includes two additional attributes, index (matches in the position of the string), and input (the string that applies the regular expression). The first string in the array that matches the entire pattern, and the other is a string that matches the capturing group in the pattern (if there is no capturing group in the pattern, the array contains only one item)
var text = "Mom and dad and baby";
var pattern =/mom (and dad (and baby)?)? /gi;
var matches = pattern.exec (text);
alert (Matches.index);
alert (matches.input);
Alert (matches[0]);
Alert (matches[1]);
Alert (matches[2]);
If you do not set a global flag, calling exec () multiple times on the same string will always return information for the first occurrence, and in the case of setting the global flag, each call to EXEC () will continue to find the new match in the string sheet
The test () method, which accepts only one string parameter, returns true if the pattern matches the parameter, otherwise returns FALSE. Often placed in an if statement
The Tolocalstring,tostring method inherited by the RegExp instance returns the literal of the regular expression, regardless of how the regular expression is created
ValueOf returns the regular expression itself
RegExp Constructor Properties
These properties apply to all regular expressions in the scope and vary based on the last regular expression operation performed, and can be accessed by long property names and short property names
Long attribute Name |
Short attribute Name |
Description |
Input |
$_ |
The last string to match |
Lastmatch |
$& |
Last Occurrence |
Lastparen |
$+ |
Last matched capture group |
Leftcontext |
$` |
The text before the lastmatch in the input string |
Multiline |
$* |
Boolean value, whether all expressions use multiline mode |
Rightcontext |
$ |
The text after lastmatch in the input string |
Regexp.$1-9, used to store first, second, and nineth matching capturing groups that are automatically populated when the exec () or test () method is executed
Function type
Each of these functions is an instance of a function type, with properties and methods like other reference types (the function is an object, and the function name is actually a pointer to a function object, not a binding). To access a pointer to a function without executing a function, you must remove the parentheses after the function name
function sum () {}
Or
var sum = function () {};
Or
var sum = new Function ()//not recommended
No Overloads
Since the function name is just a pointer, declare two functions with the same name, and the following function overrides the previous function (the second variable overrides the first one)
function declarations and function expressions
function declaration: The parser first reads the function declaration so that it is available before executing any code, and as for the function expression, it must wait until the parser executes to the line of code where it resides before it is actually interpreted.
There is no error, and the following is an error, because a reference to the function is not saved in the variable sum until the statement is executed.
SUM (10,10);
function (num1,num2) {
returnnum1+num2;
}
Or
var sum = function (num1,num2) {
returnnum1+num2;
}
function as a value
The function name itself is a variable, so the function can also be used as a value, not only to pass a function to another function like passing a parameter, but also to return a function as the result of another function.
Used to pass a comparison function to the Sort function (comparison rule, the default is the ToString Method confirmation order)
function Internal Properties
Arguments and this two objects
-where arguments is primarily used to hold function arguments, but this object also has a callee property that has a pointer to the function that owns the arguments object, that is, Arguments.callee () points to the original function
-this– refers to the environment object that the function is executed in (when the function is called in the global scope of the Web page, the This object refers to window)
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
Console.log (This.color);
}
Saycolor ();//"Red"
O.saycolor = Saycolor;
O.saycolor ();
ECMAScript 5 regulates the properties of another function object: Caller (a reference to a function that invokes the current function, or null if the current function is called in the global scope)
When in strict mode, Arguments.callee will cause errors, Arguments.caller will also error, unlike function caller, strict mode can not assign a value to the caller property of the function
properties and methods of functions
Each function contains the length (the number of named arguments the function expects to receive) and prototype (the real place where all of their instance methods are saved).
In ECMAScript 5, the prototype property is not enumerable and for-in cannot be found
Each function contains two non-inherited methods, apply () and call ()
Both of these methods are functions that are called in a particular scope and actually equal the value of the this object in the body of the function;
- The Apply () method receives two parameters: a scope in which the function is run, and an array of arguments (which can make an array or arguments object)
- The call () method works the same as the Apply method, except that the parameter is received differently, the first parameter is this, and the remaining arguments are passed directly to the function
- The powerful part of these two functions is the ability to expand the scope in which functions run
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
Console.log (This.color);
}
Saycolor ();//"Red"
Saycolor.call (this);//"Red"
Saycolor.call (window);//"Red"
Saycolor.call (o);//"Blue"
The biggest benefit of using these two methods to extend the scope is that the object does not need to have any coupling with the method
- ECMAScript 5 also defines a method, bind (), which creates a function instance where this is bound to the value passed to the bind () function.
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
Console.log (This.color);
}
var objectsaycolor = Saycolor.bind (o);
Objectsaycolor ();//blue
- The toLocaleString and ToString and valueof methods always return the code of the function
Basic Package Type
3 Special Reference Types Boolean, number, and string (each time a basic data type is read, the background creates an object of the corresponding basic wrapper type. You can call some methods to manipulate the data: 1. Create an instance of type string, 2. Call the specified method 3. Destroying instances)
reference types and basic wrapper types
The difference is in the lifetime of the object: an instance of a reference type that remains in memory until the execution flow leaves the current scope, and an object that automatically creates a basic wrapper type that is destroyed immediately after the execution of the code, which means that we cannot add properties and methods to the base type at run time;
Calling typeof for an instance of the base wrapper type returns "Object"; all objects are converted to True when Boolean operations occur.
The Object constructor also returns an instance of the corresponding base wrapper type to the factory method.
typeof (number (value))//Transformation function, "number"; typeof (Value)//constructor, "Object";
Boolean Type
var bobject = new Boolean (TRUE)
The Boolean type overrides the ValueOf method, returns the base type True or FALSE, overrides the ToString () method, and returns the string "true" "false";
Detect Boolean object result (recommended never to use Boolean object) Focus content
typeof Falseobject; Object
typeof Falsevalue; Boolean
Falseobject instanceof Boolean; True
Falsevalue instanceof Boolean;//false
Number type
var numberobject = new number (10);
Similar to the Boolean type, it also overrides the ValueOf method, returns a numeric value of the base type, overrides the ToString () method, returns a numeric value in the form of a string, and ToString () can also pass a parameter that represents the cardinality, telling the string that returns a few binary values;
methods for numeric formatting to strings
toFixed () method
A string representation of the numeric value returned by the specified decimal place; The number passed in represents a few decimals
toexponential () method
The passed-in parameter indicates the number of decimal digits in the output result 10.toExponential (1);//"1.0e+1"
toprecision () Method
It is possible to return a fixed size format (fixed) or return an exponential format (exponential) to see which format is appropriate. The method takes a parameter that represents the number of digits of all digits (without the exponential portion)
Direct instantiation of number type is not recommended
var num = 99;
Num.toprecision (1);//"1e+2"
Num.toprecision (2);//"99"
Num.toprecision (3);//"99.0"
String Type
You can use constructors to create
var stringobject = new String ("HelloWorld");
The method of a string object can be accessed at all basic string values. where the valueof (), toloaclestring (), ToString () methods return the base string value represented by the object
Length: Even if the string contains double-byte characters (not a single byte of ASCII characters, each character is still counted as one character, which is "happy". Length;//2)
Character Method
Methods for accessing attribute characters in strings: CharAt () and charCodeAt (), which are based on the 0 character position;
CharAt () returns the character of the given position as a single character string, "happy." CharAt (1);//' Xing '
charCodeAt () returns the character encoding
string Manipulation Methods
Concat: Stitching one or more strings into their Ali, returning a new string (more in practice with the plus operator)
Slice, substr, substring methods, (can receive one or two parameters, do not change the original string) The first argument is the beginning of the specified string
Where the slice and substring methods, the second parameter specifies where the substring ends, and substr is the number of characters returned, and if there is no second argument, the length of the string is used as the end position.
when passing parameters to negative values, they behave in the same way
where slice () adds the passed negative value to the length of the string, and substr adds the negative first argument to the string length, and the negative second to 0,substring converts all negative values to 0;
SUBSTRING (3,0)//This method will start from a smaller number, equivalent to substring (0,3), slice No, slice (4,3) will get an empty string
the location method of the string
IndexOf and LastIndexOf, search for the given substring from the string, and return the position of the substring, or 1 if not found; but a backward search (indexOf), one from the back forward (LASTINDEXOF)
You can receive the second argument, which indicates where the string starts searching
With the second argument, you can call indexof or LastIndexOf to find all the matched substrings by looping
Key to
pos = Stringvalue.indexof ("E", pos+1);
Trim () Method
A copy of the string is created, all spaces of the predecessor and suffix are removed, and the result is returned
String Case Conversion method
toLowerCase, toLocaleLowerCase, toUpperCase, toLocaleUpperCase
Using this time zone method is more secure when you do not know which language the code will run in.
pattern matching method for strings
The match () method is essentially the same as the RegExp exec () method, which accepts only one parameter, either a regular expression or a RegExp object; Returns an array that is the same as the Exec method
The search () method, which is the same as the match method parameter, returns the index of the first occurrence of the string, or 1 if not, and always looks backwards from the beginning of the string
The replace () method receives two parameters: the first argument can be a regexp or a string (it is 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, and all substrings are replaced. You can only provide a regular expression, and you have to have a global designation flag, the second argument can make a string, or you can make some special sequence of characters;
character sequence |
replace text |
$$ |
$ |
$& |
Matches the entire pattern of strings |
$ ' |
Substring before matching substring |
$ ' |
String substring after matching substring |
$n |
Match first N captured substrings, 0~9, no capturing group defined is an empty string |
$nn |
Matches the first NN captured substring, 01~99 does not define a capturing group is an empty string |
The second argument to the Replace method can be a function that passes three arguments to the function, a match for the pattern, its position in the string, the original string, in the case of only one match
Split Method
Splits a string into substrings based on a specified delimiter and puts it in a numeric value, either as a string or as a RegExp object, which does not treat the string as a regular expression, and split can receive the second argument, which specifies the size of the numeric value. To ensure that the returned array does not exceed the given size
Localecompare Method
Compares two strings, a string that is preceded by a string parameter in the alphabet, returns a negative number, is equal, returns 0, and then a positive number
Formcharcode Method
Receives one or more character encodings, converts them into a string, and charcodeat the counter-operation
Monomer built-in objects
Before the ECMAScript is executed, no instantiation is shown
-Global Object
Encoding Method
The encodeURI () and encodeURIComponent () methods can encode URIs to send to the browser
encodeURI: Used primarily for the entire URI and does not encode special characters that belong to the URI, such as colons, forward slashes, question marks, and # numbers
encodeURIComponent: Used primarily for encoding a segment of a URI that encodes any non-standard characters he discovers
Corresponding decoding for decodeURI and decodeURIComponent
eval () Method
Accept only one parameter, to execute the ECMAScript string, like a full ECMAScript parser
Do not use, in strict mode, external access to any functions and variables created in eval
Global properties of the object
Property |
Description |
Property |
Description |
Undefined |
Special value undefined |
Date |
Constructor date |
NaN |
Special Value Nan |
Regexp |
Constructor RegExp |
Infinity |
Special Value Infinity |
Error |
Constructor error |
Object |
Constructor Object |
Evalerror |
Constructor Evalerror |
Array |
Constructor array |
Rangeerror |
Constructor Rangeerror |
Function |
constructor function |
Referenceerror |
Constructor Referenceerror |
Boolean |
Constructor Boolean |
SyntaxError |
Constructor SyntaxError |
String |
Constructor string |
TypeError |
Constructor TypeError |
Number |
Constructor number |
Urierror |
Constructor Urierror |
window Object
All variables and functions declared in the global scope are properties of the Window object
Math Object
Math properties of the object
E, LN10, LN2, LOG2E, log10e, PI, Sqrt1_2, SQRT2
min and Max Methods
Pass in any number of numeric parameters
The maximum value and the minimum value of Math.max.apply (Math,array) are obtained.
Rounding Method
Math.ceil () performs an upward rounding
Math.floor () performs a downward rounding
Math.Round () performs standard rounding
Random Method
function (Lower,upper) {
VarChoice = Upper-lower;
Returnmath.floor (Math.random () *choice+lower);
}
JavaScript Chapter Fifth