Getting Started with JavaScript two

Source: Internet
Author: User
Tags function definition map data structure natural logarithm square root

function ******** Function Definition * *//Common function DefinitionsfunctionF1 () {Console.log ("Hello word!")}//functions with ParametersfunctionF2 (A, b) {console.log (arguments);//built-in arguments objectsConsole.log (arguments.length); Console.log (A, b);}//function with return valuefunctionsum (A, b) {returnA +b;} SUM (2, 3);//anonymous function ModevarLam =function(A, b) {returnA +b;}; Lam (2, 3);//Execute function immediately(function(A, b) {returnA +b;}) (1, 2); add: "Arrows" are allowed in ES6 (=) to define the function. varf = v = =v;//equivalent tovarf =function(v) {returnv;} If the arrow functions do not require arguments or require multiple arguments, use parentheses to represent the parameter part:varf = () = 5;//equivalent tovarf =function(){return5};varsum = (NUM1, num2) = Num1 +num2;//equivalent tovarsum =function(NUM1, num2) {returnNUM1 +num2;}* * The arguments parameter in the function * *functionAdd (A, b) {Console.log (a+b); Console.log (arguments.length)}add (The) Output:32Note: A function can only return a value, and if you want to return more than one value, you can only place it in an array or object.* * Global variables and local variables and scopes for functions * *Local variables: Variables declared inside a JavaScript function (using thevar) is a local variable, so it can only be accessed inside the function (the scope of the variable is inside the function). As soon as the function is complete, the local variable is deleted. Global variables: Variables declared outside of a function are global variables, and all scripts and functions on a Web page can access it. Variable lifetime: The lifetime of JavaScript variables begins at the time they are declared. Local variables are deleted after the function is run. Global variables are deleted after the page is closed. The scope first looks for the variable inside the function, does not find the outer function to find, and gradually finds the outermost layer. Lexical Analysis * * * *in JavaScript, the lexical analysis is performed at the moment the function is called. The process of lexical analysis: When a function call is preceded by an active object: Avtive object (AO), and analyzes three aspects:1The . function parameter, if any, assigns the secondary parameter to AO, and the value is undefined. If not, no action is made. 2. function local variable, if there is a value with the same name on the AO, no action is done. If not, the secondary variable is assigned to AO, and the value is undefined. 3The . function declaration, if available on the AO, overrides the object on the AO. If not, no action is made. Inside the function, either use a parameter or use a local variable to find it on the AO. Example 1:varAge = 18;functionfoo () {console.log (age); varAge = 20; Console.log (age);} Foo (); Example 2:varAge = 18;functionfoo () {console.log (age); varAge = 20;  Console.log (age); functionAge () {Console.log ("Hello"); } console.log (age);} Foo (); Analysis process: Lexical analysis process:1, analysis parameters, have a parameter, form a ao.age=undefine;2, analysis variable declaration, there is avarAge , found that the AO had already had a ao.age, and therefore did not do any processing3, analysis function declaration, there is afunctionAge () {...} declares that the original age is overwritten with ao.age=function(){...}; Finally, the attribute on the AO has only one age, and the value is a function declaration execution: NOTE: All values in the execution are looked up from the Ao object.1, when the first Console.log (age) is executed, the ao.age at this time is a function, so a function of the first output2. This sentencevarage=20; is a property assignment to Ao.age, at which point the ao.age=20, so the second output is 203, the third output is 20, because there is no longer a statement that changes the age value.Built-in objects and methods ******all things in JavaScript are objects: strings, numbers, arrays, dates, and so on. In JavaScript, objects are data that owns properties and methods. Note Var S1= "abc" and var s2 =NewThe difference between String ("abc"):typeofS1--String andtypeofS2--Object type built-in objects and methods introduction data type Number numeric object string string Object            Boolean Boolean object combination object array Array object math Math Object             Date Day Object Advanced Objects object custom Object Error Object Function Function object REGEXP Regular Expression object Golobal global ObjectCustom Objects * * * *JavaScript Objects (object) are essentially collections of key-value pairs (hash structures), but only strings can be used as keys. varA = {"name": "Tom", "Age": 18};console.log (a.name); Console.log (a["Age"]); The contents of the Variable object:varA = {"name": "Tom", "Age": 18}; for(varIincha) {Console.log (i, A[i]);}* * Create Object * *varperson=NewObject ();//Create a Person objectPerson.name= "Tom";//the Name property of the person objectperson.age=18;//The Age property of the person objectNote: The map data structure is available in ES6. It is similar to an object and a collection of key-value pairs, but the scope of the key is not limited to strings, and various types of values (including objects) can be used as keys. In other words, the object structure provides a "stringValue, the map structure provides a value-value "corresponds to a more complete implementation of the hash structure. varm =NewMap ();varo = {p: "Hello World"}m.set (O,"Content"}m.get (o)//"Content"M.has (o)//trueM.Delete(o)//trueM.has (o)//falseExtensions://Parent class ConstructorsvarCar =function(Loc) { This. loc =Loc;};//Parent class MethodCar.prototype.move =function () {   This. Loc + +;};//sub-class constructorsvarVan =function(Loc) {Car.call ( This, loc);};//methods that inherit from the parent classVan.prototype =object.create (car.prototype);//Fix ConstructorVan.prototype.constructor =Van;//extension MethodsVan.prototype.grab =function () {  /* ... */};Data object ****** Creating object **/Method 1: Parameter not specifiedvarD1 =NewDate (); Console.log (d1.tolocalestring ());//Method 2: The parameter is a date stringvarD2 =NewDate ("2004/3/20 11:12"); Console.log (d2.tolocalestring ());varD3 =NewDate ("04/03/20 11:12"); Console.log (d3.tolocalestring ());//Method 3: The parameter is of millisecondsvarD3 =NewDate (5000); Console.log (d3.tolocalestring ()); Console.log (D3.toutcstring ()) ;//Method 4: Parameter is month day hour minute seconds millisecondvarD4 =NewDate (2004,2,20,11,12,0,300); Console.log (d4.tolocalestring ()); //milliseconds do not show directlyMethods for **data Objects * *varD =NewDate ();//getDate () Get Day//GetDay () Get Week//GetMonth () Get month (0-11)//getFullYear () Get the full year//getYear () get year//getHours () Get hours//getminutes () Get minutes//getseconds () Get seconds//getmilliseconds () get milliseconds//GetTime () returns the cumulative number of milliseconds (from 1970/1/1 midnight)JSON object ******varstr1 = ' {' name ': ' Tom ', ' Age ': 18} ';varObj1 = {"Name": "Tom", "Age": 18};//JSON strings converted to Objectsvarobj =Json.parse (str1);//object into a JSON stringvarstr =json.stringify (obj1);RegExp object ******//RegExp Object//To create a regular object mode 1//parameter 1 Regular expression (cannot have spaces)//parameter 2 matching pattern: Common g (global match; Find all matches, not stop after first match) and I (ignoring case)//The user name can only be English letters, numbers, and _, and the first letter must be an English letter. The minimum length must not be less than 6 bits and the longest cannot exceed 12 bits. //How to create a RegExp object (do not add spaces after commas)varREG1 =NewREGEXP ("^[a-za-z][a-za-z0-9_]{5,11}$");//a string that matches the responsevarS1 = "Bc123";//the test method of the RegExp object that tests whether a string conforms to the corresponding regular rule and the return value is true or false. Reg1.test (S1);//true//How to create 2///fill in regular expressions/match patterns (do not add spaces after commas)varREG2 =/^[a-za-z][a-za-z0-9_]{5,11}$/; reg2.test (S1); //true//4 Methods for combining string objects with a regularvars2 = "Hello World"; S2.match (/O/G);//["O", "O"] finds the contents of the string that conform to the regularS2.search (/h/g);//0 Finding the content location in a string that matches a regular expressionS2.split (/o/g);//["Hell", "w", "Rld"] cut the string by regular expressionS2.replace (/o/g, "s");//"Hells Wsrld" replaces the string with a regular//A simple example of a matching pattern: G and IvarS1 = "Name:tom age:18a"; S1.replace (/a/, "hahaha");//"n hahaha me:tom age:18a"S1.replace (/a/g, "hahaha");//"n hahaha me:tom hahaha ge:18a" global matchS1.replace (/a/gi, "hahaha");//"n hahaha me:tom hahaha ge:18 hahaha" case insensitive//Note 1://if Regexpobject has a global flag, the G,test () function does not look at the beginning of the string, but instead begins at the index specified by the property regexpobject.lastindex. //the property value defaults to 0, so the first time is still looked up from the beginning of the string. //when a match is found, the test () function changes the value of Regexpobject.lastindex to the next index position of the last character of the match in the string. //when the test () function is executed again, the lookup begins at the index position, which finds the next match. //Therefore, when we use the test () function to perform a match, if you want to re-use the test () function to find from scratch, you need to manually reset the value of Regexpobject.lastindex to 0. //if the test () function can no longer find text that matches, the function automatically resets the Regexpobject.lastindex property to 0. varREG3 =/foo/G;//at this time regex.lastindex=0Reg3.test (' foo ');//returns True//at this time regex.lastindex=3Reg3.test (' Xxxfoo ');//or return True//So when we use the test () method to verify that a string matches exactly, be sure to add the ^ and $ symbols. //Note 2 (speak up you may not believe the series)://when we call the Regexpobj.test () method without arguments, it is equivalent to executing regexpobj.test ("undefined"), and/undefined/.test () returns True by default. varREG4 =/^undefined$/; Reg4.test ();//returns TrueReg4.test (undefined);//returns TrueReg4.test ("undefined");//returns Truemath******ABS (x) The absolute value of the return number. EXP (x) returns the exponent of E. Floor (x) is rounded down with a logarithmic. Log (x) returns the natural logarithm of the number (bottom is e). Max (x, y) returns the highest value in X and Y. Min (x, y) returns the lowest value in X and Y. The POW (x, y) returns the y power of X. Random () returns0 ~ 1the random number between. Round (x) rounds the number to the nearest integer. Sin (x) returns the sine of the number. SQRT (x) returns the square root of the number. Tan (x) returns the tangent of the angle. 

Getting Started with JavaScript two

Related Article

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.