JavaScript Elevation Note-------Fifth Chapter reference type

Source: Internet
Author: User
Tags array length object object prev time in milliseconds

I. Type of Object

1.1 How to create ①new keyword: var person = new Oject ();

② Given direct volume:

var person = {name: ' Zhangsan ', age  : ' 18 '}

1.2. Access mode: One for the object Point property name "Person.name" or use the brackets "person[" name "]" use the brackets must be enclosed in quotation marks or parentheses use variables such as: Var b= "name"; Person[b]

Two, array type

An ordered list of data that belongs to other programming languages, but it can store any data type.

2.1 Declaration Way ①new Object Way var a = new Array ();  Create an empty array of length 0, or pass in a number specifying the length of the array var b = new Array (5), create an array of length 5, or pass in the specified value var b = new Array ("Lisi"); Note: The array length is initialized only when a number type data is passed in, var b = new Array (5, "Lisi"), the array b at this time is 2 for the first value of type 5, and the second value is the string type "Lisi" which declares the To omit the new keyword

② Direct amount var person = new Object ();   var B = [5, "Lisi", person]; The first value of array B is number type data 5, the second value is the string "Lisi", and the third value is the object objects person! var b = []; At this point B is an empty array, the wonderful writing var a = [up,] var b = [,,,] A array may exist 2 or 3 values the third item is undefined and B may contain 3 or 4 undefined values ECMASCR The bug in IPT

2.2 The Length property of the array var b = new Array (5);  Alert (b.length) equals 5, and the length property of the array in JS is not a read-only property so you can use this attribute to implement adding data at the end of the array var b = [];  b[b.length]=5;  B[b.length] = "Zhangsan"; alert (b.length); The last B.length value is equal to 2;

2.3 Detection is an array

var value = [1,2,3];if (value instanceof Array) {//coding ...} Or if (Array.isarray (value)) {//coding ...}

The flaw in the first way is that when a Web page is communicating, because page A is not the same global execution environment as page B, and there are two different versions of the array constructor, it might fail validation! In order to resolve this issue ECMAscript 5 new Array.isarray () method This method only cares if the variable is an array type and does not care where the execution environment is created

2.4 JS Array features---stack (last-in-first-out)

Because the length property of an array is not read-only, the data store that can implement the stack structure is the push () and the Pop () method, respectively, when the push () method is called and the data is inserted at the end of the array, the array length +1! The Pop method pops the last element of the array, and the array length-1;

2.5 JS Array Attribute---queue (first-in-first-out) shift () and Unshift () method The shift method gets the value of the first element within the array and moves the value of the second element in the array to the position of the first element, and the Unshift () method Instead, insert a new value onto the first element of the array, and the original first element becomes the second element!

2.6 Array reordering reverse () and the sort () method, the reverse method is used to reverse the order of the array, and the sort method is sorted by the size of the values note that the sort method takes the ToString method of each element to get the string and then compares it against the string Sample code

var b = [0,1,5,10,15]b.sort (); alert (b); 0,1,10,15,5

The custom comparer uses sort () for sorting

function Compare1 (value1,value2) {if (value1 > value2) {return-1;} else if (value1 < value2) {return 1;} Else{return 0;}} function Compare2 (value1,value2) {return value1-value2;} var values = [0,1,5,15,10,7,9,8]values.sort (compare2); alert (values);

The Concat () method is called by the array object, copies the data from the original object, and then generates a new array object based on the parameter, accepting one or more arguments or arrays to insert the accepted arguments into the new array.

The slice () method creates a new array based on one or more elements in the current array to accept one or two parameters (the index of the parameter array) when the parameter is a truncated array in which the specified subscript starts to the element at the end of the array, and two parameters intercept the Startindex,endindex The element that creates a new array returns features that contain heads without tails!

Splice () method The main user inserts elements into the array according to the number of parameters to form a different function The first parameter is the starting position, the second parameter is the number of deletions, the third parameter: Or the nth parameter is a value inserted into the array

Two parameters---array delete element usage splice (0,2) means to delete the values of two elements in the array starting from 0 subscript

var values = [0,1,5,15,10,7,9,8];var value1 = Values.splice (0,2); alert (values); [5,15,10,7,9,8]

Three parameters---inserting elements into an array splice (0,2, "AA", "BB") starting from position 0 subscript to delete two elements, inserting two new elements can also say array element substitution function

var values = [0,1,5];var value1 = Values.splice (0,2, "AA", "BB"); Alert (values)  ; [' AA ', ' BB ', 5]

The IndexOf () and LastIndexOf () methods find the element one or 2 parameters the first parameter is the element to find, and the second argument is the lookup's starting position lookup method for the full type equality lookup "= = ="

Iterative methods for arrays These methods all accept a specified function

Every () runs the specified function for each element of an array, and returns True if each of the corresponding functions of each element in the arrays returns false.

Fiter () Each element of an array runs the specified function returns a new array of elements that return a function of true

ForEach () runs the specified function with no return value for each element of the array

Map () runs an array for each element of the specified function that returns the result of the function run

Some () runs the specified function for each element of an array, and returns True if an element corresponding function in the arrays returns false.

var values = [0,1,5,15,10,7,9,8]var Everyvalue = Values.every (function (item,index,array) {return item >=  0;}); Console.log (everyvalue);  Truevar somevalue = values.some (function (item,index,array) {return item >=  5;}); Console.log (somevalue);  Truevar Fitervalue = values.filter (function (item,index,array) {return item >=  0;}); Console.log (Fitervalue); [0, 1, 5, N, 7, 9, 8]var mapvalue = Values.map (function (item,index,array) {return item >=  5;}) Console.log (Mapvalue);  [False, False, True, True, True, true, True]

  

The reduce () and reducerigth () methods perform the given function in order and reverse the execution of the given function, eventually traversing the entire array of subkeys to execute the specified function, the first parameter in function is the value of the first element of the array, the second is the current element value, and the third is the index of the element. Four arrays of objects

This method begins the traversal of the second element of the array

var values = [1,2,3,4,5];var sum1 = Values.reduce (function (Prev,cur,index,array) {
Console.log (index); 1,2,3,4return prev + cur;}); alert (sum1); 15var sum2 = values.reduceright (function (Prev,cur,index,array) {
Console.log (index); 3,2,1,0return prev + cur;}); alert (sum2);//15

  

Third, date type

The date type in JavaScript uses the number of milliseconds in UTC time (0 O'Clock midnight, January 1, 1970) to hold the time information, var date = new Date (); Default gets the current time value if you need to create a Date object based on a specified time, you need to pass in the number of milliseconds that represent that datetime (that is, the UTC time in milliseconds of the specified time).

Date.parse (); The date string that receives the specified format is converted to milliseconds if the passed-in string cannot represent a date, this method returns Nan, and when the string is passed in the constructor of the date object, JS background parsing also gets the number of milliseconds by calling the Date.parse () method

The DATE.UTC () method also returns the number of milliseconds that represent the specified date, and its parameters are months based on the year 0 (January is 0, February is 1 ...). ), Days of the Month (1-31), Hours (0-23), minutes (0-59), Seconds (0-59), milliseconds (0-99) and only the year and month in these parameters are the necessary parameters, others do not pass, will default to 0

ECMAscript 5 new Date.now () method returns the millisecond value of the current time other methods of the Date object specific lookup document JS Elevation 102 page

Four, the regular expression type RegExp

var expression = new RegExp ("")

Pattern: Expression Format

Flags: identifier G: Indicates that all strings are matched instead of stopping immediately after the first occurrence is found, I: Indicates case-insensitive m: indicates multiline mode

Sample code

var expression =/[bc]at/i;var str  = ' cat '; alert (Expression.test (str));  True   I: Indicates ignoring case var expression =/[bc]at/g; var str  = ' cat '; alert (Expression.test (str));//True   g: indicates matching all

Metacharacters used in regular expressions must be escaped

Instance methods for RegExp objects

The exec () method captures a string of matches that returns an array of the captured string but differs from the normal array by providing an index and input property with an indexed position that matches the indexes, and input represents a string that applies the regular expression

The test () method returns a Boolean value that only verifies whether the containing compliant string object contains a return of true otherwise returns false

Verifying the mailbox format using JS regular expressions

var pattern =/^[a-z0-9]+ ([. _\\-]*[a-z0-9]) *@ ([a-z0-9]+[-a-z0-9]*[a-z0-9]+.) {1,63} [A-z0-9]+$/gi;var str1 = "[email protected]"; var str2= "swb163.com"; Alert (Pattern.test (STR1));  Truealert (Pattern.test (str2));  False

  

V. Type of Function

each function in JS is an instance of a type of function, so the name of the functions as pointers to function instances in the stack memory, examples of functions declaration: They're almost identical in meaning.

①var sum = function (num1,num2) {return num1+ num2};

②function sum (num1,num2) {return num1+num2}//Refer to anonymous objects in Java

③var sum = new Function ("Num1", "num2", "return num1+num2"); This notation is not recommended (this method produces two parsing, the first parsing of the regular ECMA code, the second parsing of the string passed into the constructor)

Concept: no overloaded function with the same name produces an overlay effect

function declaration and function expression The JS parser reads the function declaration when it loads the data into the execution environment and makes it available (accessible) when executing the code, and the function expression must wait for the code location where it is executed to actually be parsed

Alert (sum (10,10)); function sum (num1,num2) {return num1+num2;} Alert (sum2 (10,10));  Error var sum2 = function (num1,num2) {return num1+num2;}

The JS parser reads and adds a function declaration to the execution environment through a process called a function declaration promotion, so even after the function declaration is called, the JS engine can promote the function declaration to the top of the execution environment, and the second function is in an initialization statement instead of a function declaration. A reference to a function is not saved until the statement where the function is executed all errors are generated when the sum2 sum is executed

5.5 Methods and properties of functions

Functions are properties and methods, functions are special objects, each function contains two properties: Length and Propertype

The Length property indicates the number of arguments the function expects to receive;

The Propertype property is the true location of instance methods that hold reference types, such as ToString () and valueof (), which are stored in the name of Propertype

The Apply () method can extend the way the function runs the environment The Apply method receives 2 parameters The first argument is the run environment of the function, the second is an array of arguments or an instance of an array, or a arguments object

The call () method acts in the same way as the Apply method, distinguishing it from the parameter's first argument as the function's run environment, and then other parameters are passed directly to the function itself as a parameter list

varNUM1 = 10;varnum2 = 10;varn \NewObject (); o["NUM1"] = 5; o["num2"] = 5;functionsum () {//This represents the current execution environment    return  This. NUM1 + This. num2;} Alert (sum.apply ( This));//result value 20 incoming Default Global window objectAlert (sum.apply (o));//result value 10 Incoming custom Object object o

By using the Apply and call methods, the decoupling of objects and methods can also be considered as function reuse.

5.6 Basic Package Type Boolen, number, and string

var S1 = ' some text '; var s2 = s1.substring (2); alert (S2)  ; Me text

JS Internal execution when reading the value of S1 will automatically create a string object S1, so you can call the substring () method and manually create a string object is the difference between the execution of the S2 assignment code after the object is immediately destroyed : The sample Code

var S1 = ' some text '; s1.color = ' red '; alert (s1.color); Undefined  var s2 = new String ("some text"); S2.color = ' red '; alert (s2.color)  ; Red

  

The number object overrides the ToString method by default, and returns a string form of numbers that can also pass in a string that represents the cardinality of a parameter that returns a corresponding numeric value based on the cardinality of the sample var num = 10; Alert (num.tostring (2));//Result value is ' 1010 '

The ToFixed () method returns an example of a string that installs the specified decimal conversion: var num = 10; Alert (num.tofixed (2))//Result for "10.00" Note to return values with rounding characteristics and IE8 and earlier versions of this method with bug IE9 after fix

The string object takes note of the usual methods of manipulating strings without modifying the value of the original string itself, but will return a new string value after execution

The CharAt () method returns the character charCodeAt () that specifies the subscript, and returns the value in the ASCII table that specifies the subscript character

Concat (); Receives one or more parameters to the end of the string, followed by the position of the argument list

Slice (), substr (), substring () character get substring method These three methods all receive one or 2 parameters, the first parameter is the sub-string in the current string subscript, the second parameter (if there is a second argument) to indicate where the substring ends, the difference The second parameter of Slice and substr represents the subscript position of the string and substr is the number of substrings that are returned

var s1= ' abcdefgh '; alert (S1.slice (2,5));   ' CDE ' starting   from subscript 2 to subscript 5 end  with head without tail alert (s1.substring (2,5));//' CDE '   starts from subscript 2 to subscript 5 end  with head not including tail
Alert (S1.SUBSTR (2,5)); ' CDEFG ' intercept   5 substrings from subscript 2  to return

  

The position of the string method IndexOf () and the LastIndexOf () method receive one or two parameters The first argument is the character to find, the second argument is the starting point for the lookup, the difference is indexOf from left to right, and LastIndexOf is looking from right to left. If the specified character is not found return-1 find the subscript position of the character

The trim () method creates a copy of a string to remove the front and suffix spaces, and then returns the result without modifying the string itself, in addition to the Google 8+ Firefox 3.5+ Browser also supports non-standard trimleft () and TrimRight () methods to remove the string's predecessor and suffix spaces respectively

toLowerCase () and toUpperCase () string case conversions toLocaleLowerCase () and tolocaleuppercase () uppercase and lowercase conversions for regions

String pattern Matching

Capturing match () is essentially the same as the Exec () method of a regular expression object. This method receives only one parameter, either a regular expression or a RegExp object that returns an array of arrays, followed by a substring that matches the regular expression

The Find search () method receives the same arguments as the match method returns the index of the first matched substring, and returns 1 from left to right to match

The Replace replace () method receives 2 parameters, the first parameter is a RegExp object or a string, the second argument is a string, or a function if the first argument is a string, then only the substring found for the first time is replaced, and if global substitution the first argument can only pass a regular expression and specify the global identity

Split Split () method receives one or two parameters The first argument is a delimiter or a regular expression object, the second parameter is the size of the returned array

string comparison localecompare () if the string is preceded by an argument string in the alphabet, a negative number is returned and the same string is returned with a positive number 0

The fromCharCode () method receives one or more parameter types that are number return parameters that correspond to the characters in the ASCII table

5.7 Monolithic built-in objects----global objects

The global object--all properties and methods defined in the global scope are the properties and methods of the object, such as common isnan,parseint ...

5.7.1 URI Encoding method

The encodeURI () and encodeURIComponent () methods can encode the URI to send the browser for parsing encodeURI encode a section of the URI, not a special character that is itself a URI, such as a colon, slash, ask Number, #, and encodeURIComponent will encode the entire URI

The decodeURI () and decodeURIComponent () methods decode An example of the encoded URI:

var URI = ' https://i.cnblogs.com/EditPosts.aspx?postid=7628143  &update=1 '; var value1 = encodeURI (URI); var value2 = encodeURIComponent (URI); Console.log (value1);  The result https://i.cnblogs.com/EditPosts.aspx?postid=7628143%20%20&update=1       encodeURI () method converts the space after the suffix PostID to ' %20 ' Console.log (value2); Https%3a%2f%2fi.cnblogs.com%2feditposts.aspx%3fpostid%3d7628143%20%20%26update%3d1     encodeURIComponent () The method is to re-encode the special characters appearing in the whole URI Console.log (decodeURI (value1));   https://i.cnblogs.com/EditPosts.aspx?postid=7628143  &update=1console.log (decodeuricomponent (value2)) ;  https://i.cnblogs.com/EditPosts.aspx?postid=7628143  &update=1

  

5.7.2 eval () method--Receives a string form of the ECMAscript parameter when the JS parser discovers the eval () method, its arguments are parsed and the script parsed by the Eval () method is considered part of the current execution environment and therefore The executing code has the same scope chain as that of the execution environment when strict mode is not accessible outside the variable that the method resolves to execute

5.7.4 Window object----Browser's default execution environment any global variables or methods defined in JS are part of this object reference eighth chapter

The 5.7.5 Math object provides a series of mathematical formula calculations

The min () and Max () methods receive multiple parameters to return the smallest or largest parameter value in the array of the maximum value var array = [3,5,9,6,15,28,7] var max = Math.max.apply (math,a Rray);

The Ceil () method performs an upward rounding such as math.ceil (5.1) execution results equal to 6 for the value between X and x+1 that returns the X+1 value of this method

The floor () method rounds down the Ceil () method for example Math.floor (5.1) Execution result = 5 Returns the value of x after the value between x and X+1 is executed

Round () method standard Math rounding

The random () method produces a 0-1-free number without the 0 and 1 examples var num = math.random ()//num = 0.12121111931743789 tips for using the numbers object's to The Fixed () method gets the random number of the specified decimal place

 

JavaScript Elevation Note-------Fifth Chapter reference type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.