An instance of a reference type when the value of a reference type. In ECMAScript, a reference type is a data structure used to organize data and functionality together. Sometimes referred to as object definitions, because they describe the properties and methods that a class of objects have.
The new object is created with a constructor after the use new operator.
var person = new Object ();
5.1Object type
There are two ways to create an instance of an object:
The first is the use of the new operator followed by the object constructor
var person = new Object ();
Person.name = "Coore";
person.age = 29;
Another way is to use object literal notation
var person = {
Name: "Coore",
Age:29
};
To access object properties:
Dot notation
Person.name
Square bracket notation, the advantage is that the property can be accessed through a variable
person["Name"]
5.2Array type
Each item of the ECMAScript array can hold any type of data, and the size of the array can be dynamically adjusted to automatically grow with the addition of the data.
Basic methods for creating arrays:
The first is the use of the array constructor
var colors = new Array ();
var colors = Array (3);
var colors = new Array ("Red", "Blue", "green");
The constructor can be passed the number or the contained items, the new operator can be omitted;
The second basic approach is to use the array literal notation
var colors = ["Red", "Blue", "green"];
When reading and setting the value of an array, use square brackets and provide a 0-based numeric index of the corresponding value, which represents the value to be accessed.
COLORS[2] = "green";
The number of items in the array is saved in its Length property, which removes the item from the end of the array or adds a new item to the array.
var colors = ["Red", "Blue", "green"];
Colors.length = 2;
Alert (colors[2]);//undefined
Colors[colors.length] = "BLACK";
When a value is placed above the current array size, the array recalculates its length value equal to the last item's index plus 1:
var colors = ["Red", "Blue", "green"];
COLORS[99] = "BLACK";
alert (colors.length);//100
5.2.1 Detecting arrays
A single global execution environment
if (value instanceof Array) {//Perform certain actions
on array}
ECMAScript5 adds the Array.isarray () method to determine whether a value is an array, regardless of which global execution environment it was created in.
if (Array.isarray (value)) {//To perform certain operations on an array}
5.2.2 Conversion method
ToString (), which returns a comma-delimited string that is stitched together as a string of each value in the array.
toLocaleString (), creates a comma-delimited string of array values, calling the toLocaleString () method of each item.
ValueOf (), returns the array, calling the ToString () method of each item.
Join (), which receives a string parameter as a delimiter, returns a string containing all the array items.
5.2.3 Stack method
A stack is a last-in-first-out data structure that can restrict insertion and deletion of items.
Push (), receives any arguments, adds to the end of the array, and returns the modified array length.
Pop (), removes the last item at the end of the array, reduces the length of the arrays, and returns the removed items.
var colors = new Array ();
var Count=colors.push ("Red", "blue");
alert (count);//2
var item = Colors.pop ();
alert (item);//"Blue"
5.2.4 Queue method
The access method of the queue data structure is FIFO.
Shift (), moves the first item of the array and returns the item, minus 1 of the length of the arrays.
Unshift (), adds any item to the front of the array and returns the length of the new array.
5.2.5 re-ordering method
Reverse (), reverses the order of the array items.
Sort () to arrange the array items in ascending order. Calls the ToString () of each array item to compare the resulting string.
Sort () can accept a comparison function as a parameter.
function Compare (value1,value2) {
if (value1 < value2) {
return-1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}//from small to large
function Compare (value1,value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return-1;
} else {
return 0;
}
}//from big to small
function Compare (value1,value2) {
return value2-value1;
}//for numeric types
5.2.6 Method of operation
Concat () to create a new array based on all the items in the current array.
Slice (), which creates a new array based on one or more items in the current array, can accept one or more items, that is, to return the starting and ending positions of an item, excluding the end item. If the argument is negative, the array length is added to the number.
Splice (), inserts an item into the middle of the array. Returns the item that was deleted from the original array.
Delete: You can delete any number of items, provide two parameters, the position of the first item to delete, and the number of items to delete.
Insert: 3 parameters: Start position, 0, any number of items to insert.
Replacement: 3 parameters: The starting position, the number of items to delete, and any number of items to insert.
5.2.7 Location method
IndexOf (), two parameters: the item to find and an index that represents the location of the lookup start (optional). Looks from the beginning of the array to the end. Returns the position of the find item in the array, not found returns-1.
LastIndexOf (), with the same argument, looks from the end of the array to the beginning. Return to ibid.
5.2.8 Iterative method
Each of the five methods receives two parameters:
1. To run a function on each item, the function receives three parameters:
1. Value of the array item item
2. The position of the item in the array index
3. Array object itself array
2. The scope object that runs the function-the value that affects this. (optional)
var number = [1,2,3,4,5,4,3,2,1];
Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.
var everyresult = number.every (function (Item,index,array) {
Return (item > 2);
});
alert (everyresult);//false
Filter (): Each item in an array runs the given function, determines whether an item is contained in the returned array, and returns a list of the items that the function returns True. is useful for querying all array items that meet certain criteria.
var filterresult = number.filter (function (Item,index,array) {
Return (item > 2);
});
alert (Filterresult);//[3,4,5,4,3]
ForEach (): Runs the given function for each item in the array,
Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call. This method is suitable for creating an array containing the item corresponding to another array of one by one.
var mapresult = Number.map (function (Item,index,array) {
return item * 2;
});
alert (Mapresult);//[2,,4,6,8,10,8,6,4,2]
Some (): Runs the given function for each item in the array, or returns Ture if the function returns true for either item.
var someresult = number.some (function (Item,index,array) {
Return (item > 2);
});
alert (someresult);//true
5.2.9 Reduction method
Both of these methods iterate over all the items of an algebraic group and then build a value that is ultimately returned. Accepts two parameters:
1. A function that is called on each item, receives 4 parameters:
1. Previous Value prev
2. Current Value cur
3. Index of item
4. Array object arrays
2. As the initial value to reduce the base (optional).
var values = [1,2,3,4,5];
Reduce (), starting with the first item in the array, traversing through to the end.
var sum = values.reduce (function (Prev,cur,index,array) {
return prev + cur;
});
alert (sum);//15
Reduceright (), starting with the last item in the array, and traversing forward to the first item.
var sum = values.reduceright (function (Prev,cur,index,array) {
return prev + cur;
});
alert (sum);//15
5.3Date type
var now = new Date ();//Create a Date object, New+date the constructor, and automatically get the current datetime by not passing parameters.
Create a Date object based on a specific date and time:
Date.parse (), receives a string parameter that represents the date:
"Month/day/year", as in 6/06/2016;
"English month name day, year", such as January 12,2016;
"English days of the English months: minutes: seconds time zone", such as Tue 2004 00:00:00 GMT-0700.
YYYY-MM-DDTHH:MM:SS.SSSZ, such as 2016-06-06t00:00:00.
var somedate = new Date (Date.parse ("may 06,2016"));
var somedate = new Date ("may 06,2016");//equivalent
DATE.UTC (), the parameters are the year, based on the month of 0, days, hours, minutes, seconds, milliseconds. Year and month must be.
var y2k = new Date (DATE.UTC (2000,0));
var y2k = new Date (2000,0);
Date.now () (ECMAScript5 Add), which represents the number of milliseconds that the DateTime of this method was called, simplifies the work of parsing the code with the Date object.
var start = Date.now ();
DoSomething ();
var stop = Date.now (),
result = Stop-start;
Methods of 5.3.1 Inheritance
toLocaleString () returns the date and time in a format that is appropriate to the locale of the browser.
ToString (), returns the date and time of the time zone information, generally with military time.
ValueOf (), the millisecond representation of the return date.
5.3.2 Method of date formatting
toDateString () to display the day of the week, month, date, and year in an implementation-specific format;
toTimeString () To display hours, minutes, seconds, and time zones in an implementation-specific format;
toLocaleDateString () to display the day of the week, month, date and year in a region-specific format;
toLocaleTimeString () To display time, minutes, and seconds in an implementation-specific format;
toUTCString (), full UTC date in a format specific to the implementation;
5.3.3 Date/Time component method
GetTime (), SetTime (),
getFullYear (), getUTCFullYear (), setFullYear (), setUTCFullYear (),
GetMonth (), getUTCMonth (), Setmonth (), setUTCMonth (),
GetDate (), getUTCDate (), SetDate (), SetUTCDate (),
GetDay (), GetUTCDay (),
GetHours (), getUTCHours (), sethours (), setUTCHours (),
Getminutes (), getUTCMinutes (), setminutes (), setUTCMinutes (),
Getseconds (), getUTCSeconds (), setseconds (), setUTCSeconds (),
Getmilliseconds (), getUTCMilliseconds (), Setmilliseconds (), setUTCMilliseconds (),
getTimezoneOffset (), returns the number of minutes between local time and UTC time.
5.4REGEXP type
var expression =/pattern/flags;//Create a regular expression
FLAGS:G (Global mode)/I (case insensitive)/m (Multi-line mode);
var pattren1 =/[bc]at/i;//defined in literal form, always sharing a regexp instance
var pattern2 = new RegExp ("[Bc]at", "I");//Use the RegExp constructor, the pattern parameter is a string, in some cases you want to double-escape the string, each instance is a new instance
5.4.1RegExp Instance Properties
var pattern1 =/\[bc\]at/i;
alert (pattern1.global);//false
alert (pattern1.ignorecase);//true
alert (pattern1.multiline);//false
alert (pattern1.lastindex);//0 indicates the character position at which to start searching for the next occurrence, starting from 0.
alert (pattern1.source);//"\[bc\]at"
The Source property holds a canonical form of a string, that is, the string used in the literal form
5.4.2RegExp instance method
EXEC (), capturing group, receives a parameter, which is the string to which the pattern is to be applied, and returns only one match at a time.
Test (), receives a string parameter, and the pattern matches the parameter returns TRUE.
Both the tolocalestring () and ToString () methods inherited by the RegExp instance return the literal of the regular expression.
ValueOf () returns the regular expression itself.
5.4.3RegExp Constructor Properties
var text = "This have been a short summer";
var pattern =/(.) hort/g;
if (pattern.test (text)) {
alert (regexp.input);//this have been a short summer
alert (regexp.leftcontext);//this has been a
alert (regexp.rightcontext);//summer
alert (regexp.lastmatch);//short
alert (regexp.lastparen);//s
alert (regexp.miltiline);//false
}
Limitations of the 5.4.4 model
The following features are not supported:
1. Match the beginning and end of the string \a and \z anchor (can be used ^, $ to match the beginning and end of the string);
2. Backward lookup (support forward lookup);
3. The same set and intersection class;
4. Atomic Groups
5.Unicode Support
6. Named capturing groups (capturing groups that support numbering)
7.S and x matching modes
8. Condition Matching
9. Regular expression annotations
5.5Function type
The function is actually an object, and the function name is actually a pointer to a function object and is not bound to a function.
5.5.1 not overloaded
Think of the function as a pointer, two functions of the same name, and the following function overwrites the previous function.
5.5.2 function declaration and function expression
When the interpreter loads data into the execution environment, it reads the function declaration and makes it available before executing any code, and as for the function expression, it must wait until the interpreter executes to the line of code where it resides before it is actually interpreted.
5.5.3 as a worthwhile function
You can pass a function to another function just as you would pass a parameter, and you can return a function as the result of another function.
function Callsomefunction (somefunction,someargument) {
Return someFunction (someargument);
}
Properties inside the 5.5.4 function
Arguments is a type group object that contains all the parameters of the difference U-include function, and a callee property that points to the function that owns the arguments object.
This refers to the environment object to which the function is executed, or the this value.
(ECMASCRIPT5) Caller: holds a function reference that invokes the current function.
5.5.5 function Properties and methods
The Length property represents the number of named arguments that the function expects to receive.
Prototype are the real place where all of their instance methods are saved.
Apply () and call () are called functions in a specific scope, equal to the value of the this object in the body of the function.
Apply () receives two parameters: one is the scope in which the function is run, and the other is a parameter array (array instance or arguments object).
Call () parameter: This, the remaining parameters are passed directly to the function, and the arguments passed to the function must be enumerated individually.
Bind (), creates an instance of a function whose this value is bound to the value passed to the bind () function.
The function inherits the code of toLocaleString () and ToString () and valueof () always return the function.
5.6 Basic Package Type
Each time a base type value is read, the background creates an object of the corresponding base wrapper type.
The main difference between a reference type and a basic wrapper type is the lifetime of the object. An instance of a reference type created with the new operator is kept in memory until the execution flow leaves the current scope. Objects that are automatically created by the basic wrapper type exist only in the execution of a single line of code and are immediately destroyed.
5.6.1Boolean type
var booleanobject = new Boolean (true);//Create a Boolean object
Instances of the Boolean type override the ValueOf () method, return the base data type value True/false, override ToString (), and return the string "true", "false".
5.6.2Number type
var numberobject = new number (10);
ValueOf (), returns the value of the base type represented by the object;
toLocaleString () and ToString (), which returns a numeric value in the form of a string.
ToFixed (), a string representation of the numeric value returned by the specified decimal place.
Toexponential () that returns the string form of a numeric value expressed in exponential notation.
Toprecision (), may return a fixed-size format, or it may return an exponential format.
5.6.3String type
var stringobeject = new String ("Hello World");
The inherited valueof (), tolocalestring (), and ToString () are the basic string values represented by the returned object.
The Length property represents how many characters are contained in a string.
1. Character method
The two methods for accessing specific characters in a string are: CharAt () and charCodeAt (). All receive a parameter, which is based on the 0 character position.
var stringvalue = "Hello World";
Alert (Stringvalue.charat (1));//"E"
Alert (Stringvalue.charcodeat (1));//Output "101"
Alert (stringvalue[1]);//"E"
2. String manipulation methods
Concat (), used to stitch together one or more strings, returning a new string of stitching.
var stringvalue = "Hello";
var result = Stringvalue.concat ("word", "I");
alert (result);//"Hello world!"
alert (stringvalue);//"Hello"
var stringvalue = "Hello World";
Alert (Stringvalue.slice (3,7)); " Lo W "
Alert (stringvalue.substring (3,7)); " Lo W "
Alert (STRINGVALUE.SUBSTR (3,7)); " Lo worl "
Alert (Stringvalue.slice (3,-4)); " Lo W "
Alert (stringvalue.substring (3,-4)); " Hel
Alert (STRINGVALUE.SUBSTR (3,-4)); "" (empty string)
3. String Position method
There are two ways to find substrings from a string: IndexOf () (front-to-back search) and LastIndexOf () (Backward-forward search). Both methods search for a given substring from a string, and then return to the location of the substring.
var stringvalue = "Hello World";
Alert (Stringvalue.indexof ("O"));//4
Alert (Stringvalue.indexof ("O", 6));//7
4.trim () method (ES5)
Creates a copy of a string, removes all whitespace from the predecessor and suffix, and returns the result.
5. String Case Conversion method
var atringvalue = "Hello World";
Alert (Stringvalue.tolocaleuppercase ());//"HELLO World"//implementation for a specific region
Alert (Stringvalue.touppercase ());//"HELLO World"
Alert (Stringvalue.tolocalelowercase ());//"Hello World"
Alert (Stringvalue.tolowercase ());//"Hello World"
6. Pattern matching method for strings
var text = "Cat, bat, Sat, fat";
Match () parameter: a regular expression or RegExp object that is essentially the same as the Exec () method that calls RegExp.
var Pattreb =/.at/;
var matches = Text.match (pattern);
alert (matches.index);//0
Alert (matches[0]);//"Cat"
alert (pattern.lastindex);//0
Search (), which is a regular expression or RegExp object that returns the first matching index in the string. Used for lookup mode.
var pos = Text.search (/at/);
Alert (POS);//1
Replace (), the operation that replaces the substring, two arguments: a RegExp object or a string, a string, or a function.
var result = Text.replace ("At", "ond");
alert (result);//"Cond, Bat, Sat, fat"
result = Text.replace (/at/g, "ond");
alert (result); "Cond,bond,sond,fond"
Split (), you can split a string into multiple substrings based on the specified delimiter and place the result in an array. The delimiter can be a string, a RegExp object, and the second parameter specifies the size of the array.
var colortext = "Red,blue,green,yellow";
var colors1 = Colortext.split (",");//["Red", "Blue", "green", "yellow"]
var colors2 = Colortext.split (",", 2);//["Red", "blue"]
var colors3 = colortext.split (/[^\,]+/)//["", ",", ",", ",", ""]
7.localeCompare () method
Compares two values and returns one of the following values:
var stringvalue = "Yellow";
Alert (Stringvalue.localecompare ("Brick")),//1 letter is 1 after argument
Alert (Stringvalue.localecompare ("Yellow")),//0 equal to 0
Alert (Stringvalue.localecompare ("Zoo"))//-1 alphabet y in front of Z, negative
8.formCharCode () method
Receives one or more character encodings, and then converts them to strings, with the opposite action performed by charCodeAt ().
Alert (String.fromCharCode (104,101,108,111));//"Hello"
9.HTML method
Anchor (name) <a name= "name" >string</a>
Big () <big>string</big>
Bold () <b>string</b>
Fixed () <tt>string</tt>
FontColor (color) <font color= "Color" >string</font>
FontSize (size) <font size = "Size" >string</font>
Italics () <i>string</i>
Link (URL) <a href= "url" >string</a>
Small () <small>string</small>
Strike () <strike>string</strike>
Sub () <sub>string</sub>
SUP () <sup>string</sup>
5.7 Monomer built-in objects
Objects provided by the ECMAScript implementation that do not depend on the hosting environment, which exist before the ECMAScript program executes.
5.7.1Globel objects
All the properties and functions defined in the global scope are properties of global objects.
1.URI Encoding method
encodeURI (), which is used for the entire URI and does not encode special characters belonging to the URI itself;
encodeURIComponent (), which encodes any non-standard characters for a segment of the URI;
decodeURI (), can only decode the characters encodeURI () replaced;
decodeURIComponent (), can only decode the characters encodeuricomponent () replaced;
2.eval () method
Just like a complete ECMAScript parser, only one parameter is accepted, that is, the ECMAScript string to execute.
Eval ("Alert (' Hi ')"), equivalent to alert ("HI");
Properties of 3.Global Objects
Undefined NaN Infinity Object Array Function Boolean String number
Date RegExp Error evalerror rangeerror referenceerror syntaxerror TypeError urierror
4.window objects
The Web browser implements this global object as part of the Window object.
5.7.2Math objects
Save mathematical formulas and information.
Properties of 1.Math Objects
Base of natural logarithm of MATH.E
Natural logarithm of Math.ln10 10
Natural logarithm of MATH.LN2 2
MATH.LOG2E logarithm of base e of 2
math.log10e logarithm of base e of 10
The value of the math.piπ
Square root of Math.sqrt1_2 1/2
Square root of Math.sqrt2 2
2.min () and Max () methods
Used to determine the minimum and maximum values in a set of values.
var values = [1,2,3,4,5,6,7,8];
var max = Math.max.apply (math,values)
3. Rounding Method
Several ways to round a decimal number to an integer
Alert (Math.ceil (25.9));//26 rounding up
Alert (Math.floor (25.9));//25 Rounding down
Alert (Math.Round (25.9));//26 Standard rounding
4.random () method
Returns a random number between 0 and 1
function Selectfrom (lowervalue,uppervalue) {
var choices = Uppervalue-lowervalue + 1;
Return Math.floor (Math.random () * choices + lowervalue);
}
5. Other methods
Math.Abs (num) returns the absolute value of num
MATH.EXP (NUM) returns the NUM power of the MATH.E
Math.log (num) returns the natural logarithm of num
Math.pow (Num,power) returns the power sub power of num
MATH.SQRT (num) returns the square root of num
Math.acos (x) returns the inverse cosine value of x
Math.asin (x) returns the inverse sine value of x
Math.atan (x) returns the inverse tangent value of x
Math.atan2 (y,x) returns the inverse tangent value of y/x
Math.Cos (x) returns the cosine of X
Math.sin (x) returns the sinusoidal value of x
Math.tan (x) returns the tangent of X
Summarize
objects are referred to as reference type values in JavaScript, and some built-in reference types can be used to create specific objects:
The reference type is similar to the class in the traditional object-oriented programming, but the implementation is different;
object is an underlying type, and all other types inherit basic behavior from object;
The array type is an ordered list of values and also provides the ability to manipulate and transform those values;
The date type provides information about dates and times, including the current date and time, and the associated calculation function;
The regexp type is an interface that ECMAScript supports regular expressions, providing the most basic and advanced regular expression functionality.
A function is actually an instance of a function type, so it is also an object, and that is where JavaScript is most distinctive. Because functions are objects, functions have methods that can be used to enhance their behavior.
Because of the basic wrapper type, the basic type values in JavaScript can be accessed as objects. Three basic package types are: Boolean, number, String. Their common characteristics are:
Each wrapper type is mapped to the base type with the same name;
When accessing the base type in read mode, an object of the corresponding basic wrapper type is created, thus facilitating data manipulation;
The newly created wrapper object is destroyed immediately after the statement that operates the base type value is executed.
Two built-in objects already exist in the scope before all code executes: global and math. The global object is not directly accessible in most ECMAScript implementations, but the Web browser implements the Window object that assumes the color. Global variables and functions are properties of the global object. The Math object provides a number of properties and methods to aid in the completion of complex mathematical computing tasks.
Fifth Chapter reference types