Learn JavaScript natively in minutes

Source: Internet
Author: User
Tags arithmetic arithmetic operators date settime event listener naming convention string methods switch case tag name

JavaScript is an object-and event-driven, client-side scripting language that consists of the ECMAScript---------------standard syntax BOM (Browser Object Model) Dom (document)------- Browser-provided extensions Api:application programming Interface application Interface JS Introduction, internal and external, preferably placed in the body of the </body> tag before; external: <script src= "" > </script>-----maintainability is high, cacheable, can be placed in head and body, but consider the load order document.write () method, output HTML content to the browser window, So the line break in document.write () is the <br/> variable: Declare a variable with VAR to declare------var variable name = initialize value; JS is a weakly typed language that does not declare a variable type when it is defined; JS's five basic data types: strings string , integer number, Boolean boolean,null,undefined logically, a null value represents an empty object pointer, so a type is a object  variable can define multiple variables at once by using commas, and variable naming is the naming convention for identifiers. Identifiers include variables, functions, names of properties, best known by name, lowercase letters, cannot have spaces, cannot be keywords, cannot be reserved words, case-sensitive, hump-named alert () prompt box, document provides method, so line break is "/n"; Alert only receives the string as a parameter, automatically calls the ToString () method conversion; The variable definition of the string type can be used "" or "; Console.log (); The method is to output the results in the console, the Chrome browser console output, will automatically provide line break; string concatenation: + Transformation Function: Boolean---boolean (), return value is True and False, String returns True, empty string returns FALSE, value 0 returns false, other return true;null type returns false; Undefined returns false; float, type due to accuracy problem, calculation is not accurate, true is 1,false is 0, numeric----parsefloat (); The return value is a floating-point value; Parses a string and returns a floating-point value; Numeric----parseint (); The return value is an integer value, True is 1,false of 0; resolves aA string that returns an integer value that, when parsed, is a numeric value starting with 0, which, if the argument is 0, starts with a string that begins at 8, and the 0 is ignored if the argument is the value of the ox at the beginning of the parse, and the value is converted according to the 16 binary (A~f is 10~15); Display type conversion:. ToString () method, coercion type conversion, conversion to string, for null and undefined, cannot be converted, to use the string () function object: An object (), to create a new keyword, it is a set of data and functions; After creation, you can add properties and method arithmetic operators to it: +: Whenever a string appears, it becomes a string concatenation;-*/%: Call number () conversion; Assignment operation: The right value to the left variable; simple assignment operator: = Compound assignment operator: + = = *=/=%= (i + = 1; is i=i+1); Boolean operator:! && | | Logic &&: Du Jin Cai is true, if the first is false, then do not judge the second element, must be false;  logic | |: As long as a true, is true, the first is true, does not judge the second element, must be true;: Just take the counter if statement: if () {}if () {}else{}if () {}else if () {} else if () {} Else{}switch Case:switch (condition): Case 0: ... (Each case should have a break;); the condition can be written in true,case; relational operators: > < >= <= comparison rules: all strings are compared to string encoding one is numeric, The other translates to a numeric Boolean value converted to a number, true to 1,false of 0; equality relationship: = = equals! = Unequal: If the comparison type is the same: The return value is a Boolean value, equality returns True, and the comparison type is different: When you compare a Boolean, the Boolean converts to a value ; A numeric value, a string, a character converted to a numeric value; null and undefined are equal; null and undefined do not convert; As long as there is nan on the same sex relationship: = = Congruent!== not congruent: not only to compare the type, but also to compare the value; loop: for (var i = 0; I is less than the cyclic condition; i++) {loop body;}//is often used to know the loop of the number of cycles;  while (cyclic condition) {loop body; self-increment condition} Often used for loops that do not know the number of cycles;  break: Jump out of the wholeLoop continue: Jump out of this cycle, continue the program dead Loop: Due to programming errors, so that they can not control the termination of the program, because of the need, want the program to be executed, when a specific requirement to terminate the cycle of the case; browser debugging: (debug) Sources view, You can set breakpoints, you want to observe the variables can right-click Add Watch, after the refresh, clicking Next, step by step to see the execution; functions: The declaration of a code block (divided into custom functions, built-in functions) functions that can be reused: function name (parameter 1, parameter 2) {function body;} function can not have a name, we call anonymous function function can not call------function name (actual parameter 1, actual parameter 2); Understanding parameters: Function Parameters do not mind how many, or do not mind passing in the data type, that is, the definition of the time to pass in two parameters, But at the time of the call does not necessarily have to pass in two parameters, can be one, or can be three, the inside of the parameter is directly within an array, so we can access the object through the arguments objects passed to the function of each parameter; local variables and global variables: precedence: Local greater than Globally, if a variable is defined within a function, and no Var is added, then the system considers the variable to be a global variable; random number: function Randomnum (min, max) {return Math.floor (Math.random () * ( max-min+1) + min);} Event-driven: 1 get element, 2 bound event event: OnClick mouse click event ondblclick mouse Double click event onmouseover mouse move onmouseout mouse out onmouseenteronmouseleave recursive function: A function invokes its own case by name; An array: An ordered list of arrays, each of which can hold any type of data; the length of an array can be dynamically adjusted; Length: array name. length; Create: var array name = new Array[];var Array name = []; add: array name [ Position subscript]= ""; the array name. Push (A ""), add the element "a" from the last position of the array, the array name Unshift ("a"), add the element "a" from the first position of the array, and the array name. Concat (parameter 1, parameter 2 ...) method; Creates a new array based on the current array; the effect is to merge, you can merge two or more arrays, and if it is a value, it is added to the new array if it is one or more arrays, then each item in the parameter array will be added to the new array: array name. Pop (a "");The element "a"; the array name. Shift ("a"), removes the element "a" from the first position of the array, and the string: the array name. The Join ("") method is to concatenate each item in the array into a new string by a character join; sort: array name. Sort () Method: Ascending: Array name. sort (function (A, b) {return-A;}); Descending: Array name. sort (function (A, b) {return b-a;}); Reverse order: Array name. reverse () method; array Reverse lookup: array name. INDEXOF ("a") method; Find a with the first element of the array, and return the subscript value; the return-1; array name is not found. IndexOf (A, B) method; from the ground a+1 element of the array. and returns the next small array name of the found element. LastIndexOf ("a") method; finds a with the last element of the array and returns the subscript value; no return-1; intercept: array name. Slice () method; intercept array to get a word group, Accept one or two parameters a parameter is from the position of the parameter to the last intercept, two parameters are taken from the parameter 1 to the parameter 2, without the parameter 2; Accept negative arguments, negative numbers are the;   array names that are intercepted from the last item in the array. Splice () method; can implement the addition of the array delete and intercept, the parameters accept two, three or more, accept negative parameters; String object: Is the object type of the string, which can be created with a constructor; var str = new String ("content"); var str1= "content"; Basically, this is done because the basic type of string can also be used in string methods; Method: Find: String. CharAt () method; Returns the character of the given position; the string. charCodeAt () method; the encoding of the character at the given position;// The opposite approach to String.fromCharCode (); String.fromCharCode () method; A static method that receives a character encoding and turns it into a string;  string. IndexOf ("a") method; Returns a position subscript for the first occurrence in a string, if no return-1 is found; String. LastIndexOf ("a") method; Returns a position subscript for the last occurrence of a in a string, if no return-1 is found; add: String. Concat ("A", "B", "C" ...) method, not changing the original string, generating a new string added on the original string; multiple concatenation of strings; plus + string concatenation//longest use; substring: string. substring (x) method; intercept subscript x start to end of stringSUBSTRING, does not change the original string; substring (x, y) method; intercept string subscript x to Y of the substring, including x does not contain Y, does not change the original string. Slice (x); intercepts the substring starting at the end of the string, without changing the original string. Slice (x, y); Intercept string subscript x to Y of the substring, including x does not contain Y, does not change the original string. substr (x); intercepts the substring starting at the end of the string, without changing the original string. substr (x, y); intercept string subscript x start, followed by Y; do not change the original string;  Go to Space: string. Trim () method; remove whitespace from string header and tail, string. Trimleft () method, remove leftmost space of string, String. TrimRight () method, remove the rightmost space of the string, split: Splits the string into arrays according to the delimiter; Does not change the original string; solid ("Regular characters in the original string"); A regular character in the original string is not found to return 1; case conversion: String. toLowerCase () method; convert to lowercase; string. toUpperCase () method; convert to uppercase; Replace: string. replace (); accept one or two parameters, One parameter is from the subscript parameter to the last, and two parameters are parameter 2 to replace the parameter 1 string; Preserve decimal places: String. toFixed (s);  math object: The methods of this object are static methods, mathematical formulas and information, compared to the methods you write, The method provided by math is more efficient; properties:. Pi is the Pi method in Mathematics: Math.random () random number 0~1math.min (x, y); Math.max (x, y); y returns the maximum value; Math.ceil (a); a upward rounding, taking the largest integer; Math.Round (a); a mathematics rounded rounding; Math.floor (a); a downward rounding, taking the smallest integer;//usually taking into account the efficiency problem, the method is used instead of the parseint () method of rounding; Math.ads (a); Returns the absolute value of a; Math.sqrt (a); a open square; Math.pow (a,n); n times of A; Date () object: ECMAScript in the number of milliseconds elapsed since 0 o'clock midnight on January 1, 1970; Create: var variable name = new Date (); Date () system current time, when the parameter is passed, the ToString () method of the date type is automatically called; var d = new Date (year, month, day); D Date Type method: Before the method is used,A Date object must be new to be used; A Date object. getFullYear (); Gets the year; the Date object. GetMonth (); Gets the month; the Date object. GetDate (); Date object. getHours (); Gets the number of hours; Date object. getminutes (); Gets the number of minutes; the Date object. getseconds (); Gets the number of seconds;//One second = 1000 milliseconds;  date object. setFullYear (); Set year; Date object. setmonth (); Set month; Date object. Setday (); set dates; Sethours () ; Set the number of hours; setminutes (); set the Minutes; Setseconds (); Set the number of seconds;  date.now ()//The number of milliseconds for the current time; parse (2016,8,23)// Converts the date 20160823 to the number of milliseconds from January 1, 1970; GetTime (); Gets the number of milliseconds for the specified date settime (); Sets or modifies the date, based on the specified number of milliseconds, and the conversion of strings and arrays: Convert the array to a string: Arr.join ("symbol");// Each string is delimited by a symbolic string to the array: str.split ("symbol");//The string is delimited by a character rule, and the DOM: Document Object Type;  Note: label. InnerHTML = "";: writes content to the output tag, can write directly to HTML tag; top-level object: Window:window.screen Screen object window.location Address bar object Window.history The History object window.navigator the Browser object method: Window.alert ();//alert ();//Only the string parameter is received; the ToString () method is not called; Window.document.write ();/ Output content; Window.promet ("");//Prompt input box window.confirm ();//Confirm message box, return value is Boolean type if (Window.confirm ()) {alert ("You clicked OK");} Else{alert ("You clicked Cancel"); Window.onload = function () { }//page loading is done after completion;//General when requiredWrite JS in the head, it is necessary to write this, to avoid the loading sequence cannot take the element;   timer: One-time timer: setTimeout (parameter 1, parameter 2);//parameter 1 is generally a function, the parameter 2 is usually the unit of milliseconds; setTimeout (function () { }, Time (ms)), Loop timer: setiterval (parameter 1, parameter 2),///parameter 1 is generally a function, parameter 2 is generally the time interval to execute the parameter 1, in milliseconds; var Temer = SetInterval ( function () { }, Interval time (ms)), in order to be able to turn off the timer, generally in the time of writing the timer to give a variable to the return value of the timer; timer closed: cleatinterval (parameter);//parameter must be the return value of a timer; Focus Event: onfocus//Get focus onblur//Lose focus//focus event is generally more than the table alone: Form elements. onfocus = function () {}this keyword: The trigger event itself is this; // The following actions for the new window will have the new window get Focus (onfocus) window.open (parameter 1, parameter 2, parameter 3);//The method can open a new window with the specified size and position in the current window;//parameter 1:url Parameter 2: Window Name parameter 3: The string set by the window (comma separated by the value pair); Window.close ()//close new window; Window.moveto ();//Set new window position; Window.resizeto (width,height);//Set new window width height; Location object: Host Domain: Window.location.hostname current page path: Window.location.pathname full url:window.location  Method: Assign (" URL ");//pass an address, jump according to address;  reload ()//Refresh the current page; function Reloadpage () {window.location.reload ();}  rosource (); Represents the object's source code, usually by the JS automatic backstage call, does not write in the code (Firefox does not support); properties: location.href = "url";//jump based on address; understanding constructors: Constructors can create objects of the specified type. The native constructor automatically appears in the running environment at run time, and you can create a customconstructor, which defines the object type and method; The constructor itself is a function, but it can be used to create objects; By convention, constructors always start with uppercase letters; When instantiating an object: var instantiates object = new Constructor Navigator object: Browser name: Browser version: Operating System Information://above the basic no, the latest browser is as long as: navigator.useragent; Browser and operating system information;//The message is also transmitted in the header of the HTTP protocol;  screen object://Display screen window.screen.width//Width window.screen.height// High Window.screen.availWidth//available width (except taskbar) window.screen.availheight//available high (drop taskbar) History object: Properties: History.length// 0 is the new one. Page method: History.go ();//parameters are-1 and 1 for previous and next page; Scroll event (onscroll): compatible: var scrollleft = Document.body.scrollLeft | | Document.documentelement.scrollleft;var sctolltop = Document.body.scrollTop | | Method of getting elements in Document.documentelement.scrolltop;dom: document.getElementById ("id name");d Ocument.getelementsbytagname (" Tag name ");//put in the array document.getelementsbyclassname (" Class name ");//put in the array document.getelementsbyname (" name name ");//Put into the array, The element has the name attribute to fetch  document.queryselector ("CSS selector");//As long as the first one, IE8 below is not supported; Document.queryselectorall ("CSS selector");// Find all, put in the array, IE8 the following is not supported; the precedence of the expression: the parentheses can change the precedence arithmetic (+) > relationship (= =) > Logic (&&) > Assignment (=);D om tree: node: Yes contains tags, notes, text, DoctypVarious combinations of E, etc. node properties: NodeType node type return value: 1 2 3nodeName node name nodevalue node value  nodetype nodeName nodevalue element Node 1 uppercase element name (sign) null or undefined attribute node 2 property value Text node 3 #text text itself    node relationship: childNodes: All child nodes of the element (including spaces, carriage returns, Tab blanks), children: all element child nodes of the element, Does not contain a text node; FirstChild: The first child node of an element lastchild: The last child node of the element  parentnode: The parent node of the element  nextsibling: The next sibling node of the element previoussibling: the previous sibling node of the element   firstelementchild: The first child node of an element lastelementchild: The last child node of the element nextelementsibling: The next sibling of the element previouselementsibling: The last sibling of the element   node operation: check: Just get the node (six ways to get the elements in the DOM) Increase: Add two steps , create first, create in join: createelement ("attribute name");//Create Attribute node createTextNode ("");//Create Text node Plus: parent element. appendchild ("Chuang");//Add a creation to the parent; The parent element. InsertBefore ("Genesis", "Node")//Added to a node of the parent; modify: Parent. ReplaceChild ("New", "old");//The old in the parent is replaced by new; Delete: parent. RemoveChild ("node");// Delete the node in the parent. Remove ()//ie not supported; clone: node. CloneNode (True);//clone and add to new node;    get the value of a specific element node property: An element. getattribute ("attribute name");//The value of an attribute that obtains an end element is---equivalent: an element. Property name sets the value of a specific Element node property: an element. SetAttribute ("attribute name", "property value");// Sets a property and corresponding value of an element---equivalent: an element. A property = property value; Removes the attribute value for a specific element node: an element. removeAtTribute ("attribute name");//Delete an attribute of an element;----equivalent: an element. A property = "";  custom property: Custom properties are used for lazy loading pictures by convention: Data_ Property name = attribute value;   Get non-inline style attributes and property values: Compatible: if (an element. Currentstyle) {an element. Currentstyle. property name;} Else{window.computedstyle ("Some element", "null"). property name;//no Pseudo-class parameter 2 is null} offset: (relative to position parent) Offsetwidth: size occupied by element in horizontal space (content + border + padding) Offsethight: The size occupied by the element in the vertical space (content + border + padding) OffsetTop: The upper boundary of the element to the upper boundary of the parent element offsetleft: The left edge of the element to the left edge of the parent element offsetparent: The reference is the parent element   Event: is a response to a user action, used to handle form validation, and so on, and the event is usually used in conjunction with the function, and the function will no longer be executed before the event occurs; For example: User clicks: onclick ondbclick Verify user input legitimacy: onsubmit window Scrolling: onscroll page size Change :onresize   Events Object: Event is an implied element in an event that can be obtained by arguments[0], and when a DOM event is triggered, an event object is generated that contains all the information about the event, such as the mouse position, The keyboard presses inferior to block default events (compatible)://For example, right-click menu (OnContextMenu) if (event.preventdefault) {Event.preventdefault ();} Else{return false;}   Block event bubbling (compatible)://For example Li's click in the right-click menu and clicking Elsewhere ul disappears; if (event.stoppropagation) {event.stopproragation ();} Else{event.cancelbubble = true;}     Event Bindings: Tags are directly bound------< input type= "button" onclick= "func ()" >script: onclick = function () {} Addeeventlistener ("Click", functon () {}, false/true); The first argument, the event name is not on, the second argument is mostly a function, if it is not an anonymous function, write only the function name, no parentheses, a third argument, all false bubbles (bubbling is from the child element to the parent execution) are true capture ( The capture mechanism is executed from the parent element to its own element) if more than one event is bound to multiple functions, who is true first to execute who, both true to the father, all false on the bubbling;  keyboard event: Get the keyboard: Event.keycode// You can only save one value at a time onkeydown keyboard press onkeypress keyboard to press the ONKEUUP keyboard to release   keyboard combination function key: Ctrl shift ALT is a special key press CTRL Event.ctrlkey return true; Press Shift Event.shiftkey to return true; press Alt Event.altkey to return true; So the decision of the key combination:  if (event.keycode = = key code && Event.ctrlkye) {}//colleague presses CTRL and a key to perform a;  mouse event: OnClick left-click the Ondbclick button double-clicks OnContextMenu Right-click onmousedown Left-click OnMouseUp left button to open Onmusemove mouse movement onmouseover mouse move in onmouseout mouse move out   can get mouse coordinates through the event object: Event.offsetx//Relative to the event source The offset of an object is the relative coordinate of the element; the location of the Event.offsety//event.clientx//visual area is the browser coordinates event.clienty//event.offsetwidth//content +padding+border (remove margin) event.offsetheight//event.clientwidth//Content +paddingevent.clientheight//event.screenx//screen coordinates (with less) Even.screeny//event.pagex//page coordinates event.pagey//   event listener, AddEventListener ("Dbclick", function, false);//Default False ( Bubbling) Capture mechanism/bubbling: Capture is the parent child, bubblingIs the child to the parent;  event delegate; is to use the bubbling mechanism, add the event to the parent element, and then through Event.target (), find the corresponding actual target object, improve the efficiency;  cookie: the composition: name; Value Domain (with default); Expiry time (with default); Safety signs (with default); Path (with default): Semicolon and space to separate each cookie, read and write is not intuitive, so call Cookie,js (oneself write) The work of the cookie is the right to use the JS file directly, the client to store user information capacity requirements, Information belonging to a particular user should exist on that user's machine, such as login information, preferences, and so on, simply saying that a cookie is an option for storing data on the client     compatible collation: event| | Window.event (Get Event object, compatible with old IE version) stoppropagation| | Cancelbubble = True (Block event bubbling, compatible with IE old version) Preventdefault () | | return FALSE (block default event, compatible with IE) window.getComputedStyle ("", "") | | Currentstyle (get non-inline style, compatible with IE) Document.documentElement.scrollTop () | | Document.body.scrollTop (onscroll, compatible with Google) AddEventListener ("Click", Function () {},false/ture) method | | Attachevent ("onclick", function () {}) (Event listener compatible IE notation, execution sequence executed in order of binding)

Learn JavaScript native

in minutes

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.