JavaScript Essentials Summary--the most Important

Source: Internet
Author: User
Tags array length

The underlying variables of JavaScript, the detailed description of the operators, and the basic branch loop nesting are already in

JS basic variables and the operators in JS
Looping branch Nesting in JS

As I said, what we are talking about today is the longest use of web pages. The content is not small, you have to be patient, look slowly

1. Declaration and invocation of functions:

Declaration and invocation of a function:The function must be defined before it can be called .1. function definition has three parts: function name, argument list, function body Defining the format of a functionfunction name (parameter 1, parameter 2,....... ) {function execution part;return expression;}function call Format: Call directly: the function name (the value of parameter one, the value of parameter two, ...). ) The declaration invokes an anonymous function:1. Declare an anonymous function to be assigned directly to an eventevent name =function () {}window.onload=function () {Console.log ("");}2. Invoking an anonymous function using a function expressiondeclaring a function expression:var func = function () {Console.log ("");}Call Function Expression: func ();use an anonymous function expression, must be declared after the statement, or the error3. Invoke the anonymous function using the self-executing function:! function (parameter i) {} (the value of parameter one);--start with any operator, general use! (function () {} ());--use parentheses to wrap the function and subsequent contents( function () {});--use parentheses to wrap only anonymous function expressionsthree kinds of writing characteristics: ① structure is clear, beginning add! , End Plus (). Not easy to mess② can indicate that the anonymous function and the following parentheses are a whole, it is recommended to use③ cannot indicate that the function and after () are a whole, it is not recommended to use2. Several functions of the ① function declaration must conform to the small hump rule, the first letter lowercase, followed by the first letter of each word capitalized; ② parameter list can have parameters, can have no parameters, respectively, called the parameter function, no parameter function; ③ the argument list when declaring a function is calledformal parameter list (variable name);The argument list when calling a function is calledArgument list (variable value);Parameters that are actually valid in the function depend on the assignment of the argument, the parameter that is not assigned, and the Undefined④ function if it needs to return a value, you can return the result with return. When calling a function, the return result is received using the var variable name = function name; If the function does not return a value, the accepted result is the scope of the variable in the Undefined;⑤ function: variable declared with Var in the function, default to the function's local variable, only within function A variable declared with VAR, which defaults to a global variable (the global variable in the function must be used after a function call); The parameter list of a function is a local variable of the function, only within the function; ⑥ function declaration has no precedence over function invocation, that is, the call statement can be written before the declaration statementJS in the code to run, will be checked, loaded, that is, declaring variables, functions and other operationsand then the execution phase (the assignment of the variable belongs to the execution phase)The declaration of a function belongs to the check Mount stage, and the call to the function belongs to the execution phase. So where does the function call matter?Console.log (num), var num=10;funcn (), function FuncN () {} In order:--check load--①var num, ———— declare variable ②function funcN () ———— Declare function--execution phase--③console.log (num); ④NUM=10;⑤FUNCN (); Print result is undefinedproperties inside the function:"Argument object" 1. Function: The argument list that is used to hold the value assigned when the function is called; when we call a function and assign a value using an argument, the parameter is actually saved to the argument array. You can invoke parameters in the form of argument[n] even if there are no formal parameters. The number of 2.arguments arrays, depending on the argument list, is independent of the parameter. (Order zero-based) but when the N-position parameters, arguments, arguments are present, the shape participates in the arguments is synchronous, that is, modifying one of the values in the function, and the other synchronizing changes 3. Argument.callee is an important property of argument that returns a reference to the function that argument is located in:. Argument.callee can invoke its own function execution; The function itself is called recursive;

BOM in 2.JS (Browser object model)

The Window object's common method, you can omit the previous window, such as close ();
1, prompt: Pop-up window to accept user input;
2, Alert: Pop-up window warning;
3. Confirm: Prompt box with confirmation/Cancel button;
4. Close: Closes the current browser tab
5. Open: Reopen a window, incoming parameters: url/window name/Window feature
6, SetTimeout: Set delay execution, will only execute once
7, SetInterval: Set the timer, cycle every n milliseconds to execute once
Two parameters: function/milliseconds to execute
8, Cleartimeout: Clear delay
9. Clearinterval: Clear Timer
Incoming parameter: Returns an ID when calling SetInterval, passes the ID through the variable, and passes in the SetInterval

Where setting the time delay to execute and set the timer is very common, here are examples of their usage:

var timeoutid = setTimeout (function() {                console.log ("SetTimeout");            }, );            SetInterval (function() {                console.log ("setinterval");            },1000);

Dom in 3.JS

[DOM tree node]There are three main categories: element node, text node, attribute node text node and attribute node as the two child nodes of the element node. Through getElementById: Get a unique node by ID[view node]1.getElementById ("Div1") gets a unique node through an ID: multiple IDs with the same name will only take the first2.Getelementsbyname () takes an array of one or more nodes by nameUse the way, through loops, to fetch each node. Number of loops, zero-based < array. lengthGetelementsbyclassname () and getElementsByTagName are all arrays, use the same name[view and set attribute nodes]1. View the attribute node:getattribute ("attribute name");2. Set the attribute node:SetAttribute ("Property name", "Property value")"JS modified style Summary"1.className: Set a new class name for the element; Div1.classname= "Class1" 2,. Style.: Sets a new style for the element. For example: div1.style.backgroundcolor= "Red" 3.style.csstext: Modifies multiple styles for an element at the same time. For example: div1.style.csstext= "width:100px;"[view node]1. tagname Property: Gets the label's label name 2. innerHTML property: Sets or gets all HTML code 3 inside the node. InnerText: Sets or gets all the text inside the nodeEvents in 4.JS"Event classification in JS"
1. Mouse events:Click/dbclick/mouseover/mouseout/mousemove/mousedown/mouseup
2. Keyboard events:
KeyDown: Keyboard presses down to trigger
KeyPress: Instant trigger when keyboard is pressed and released
KeyUp: Triggered when the keyboard is lifted

[Note: (Learn)]
① Execution Order: Keydown-keypress-keyup
② long and on time, will cycle continuously to execute keydown-keypress
③ There is KeyDown event, there is not necessarily a KeyUp event, (during the event trigger, the mouse is moved, there may be no keyup)
④keypress can only capture letters, numbers, symbol keys, cannot capture function keys; Keydown/keyup basically captures all function keys (except special)
⑤keypress is case-sensitive, KeyDown and KeyUp do not differentiate
⑥keydown/keyup distinguishes between the main keyboard and the keypad, KeyPress does not distinguish between

"OK keyboard trigger button"
1, in the trigger process, the incoming parameter E, representing the key time;
2, through E.keycode, confirm the key ASCII code value, and then determine the key;
3, all the browser system writing (generally not necessary):
var evn = e| | event;//fetching keyboard Events
var code = evn.keycode| | evn.which| | evn.charcode;//Take the button


"The DOM0 event model in JS"
1, inline model: directly the function name as an attribute value of an event property of an HTML tag;
Eg:<button onclick= "func ()" > Buttons </button>
Cons: Violating the basic principles of HTML and JavaScript separation;
2, the script model: in the JS script through the event attribute to bind;
Eg:window.onload = function () {}
3, limitations: The same node, can only bind the same type of event

"The DOM2 event model in JS"
1. Add Event Bindings:
IE10 Before: btn1.attachevent ("onclick", function);
Other browsers: Btn1.addeventlistener ("onclick", function, True/false);
Parameter three: false (default), indicating event bubbling; True, indicating event capture
Compatible wording:
if (btn1.attachevent) {
btn1.attachevent ();
}else{
Btn1.addeventlistener ();
}

Advantage: The same node, you can add multiple listeners of the same type of event;


"Stream of events in JS"
1. Event bubbling:When a DOM element fires an event, it starts with the current DOM element, triggering the same type of event for its ancestor element, until the DOM root node
The DOM0 model is the event bubbling;
Use in IE:. attachevents () added events, all bubbling;
Other browsers:. Addeventslistener adds an event that is bubbling when the third argument is false.

2. Event Capture:When a DOM element fires an event, it starts at the root of the DOM, triggering the same type of event of its ancestor element one at a time until the current element is triggered;
Only when the event is added using. Addeventslistener and the third parameter is set to True is it captured;

↓ Current Elements ↑
↓↑
Take the father element to catch
↓↑
Bubble Grandpa Element won
↓↑
↓dom root node ↑

3. Blocking event bubbling (emphasis):
In IE: Set the E.cancelbubble property to true;
Other browsers: Call E.stoppropagation ();

Compatible wording:
function= e | | window.event; if (e.stoppropagation) {    //ie other than else  {    true//  IE}}

Here is a code to detect your keystrokes:

function (e) {                var evn = e| | event;                 var code = evn.keycode| | evn.which| | Evn.charcode;                Console.log (e);                Console.log ("KeyDown");                 if (code==13) {                    alert ("You hit enter");}            }

Arrays in 5.JS with built-in objects

1. The concept of arrays:An array is the sequence of structural elements that store multiple sequential elements in memory, called subscripts, to locate corresponding elements by subscript2. Declaration of the array:① by literal declarationvar arr1 = [,,,]js, the same array can store many different data types (typically the same array is used only for the same data type) var arr1 = [1, "2", true,{"name": "LyX"},[1,2]];② with the new keywordvar arr2 = new Array (parameter); argument can be: empty: Declares an array with no length specified; Length: declares an array of a specified length, but the length of the array is variable at any time and can be appended. The maximum length is the default n value of the 0-2^32-1 array: the new Array (1, "2", true) is equivalent to [1, "2", true]3. Read/write/delete of elements in the array:① Read and write: Access to elements through subscripts. For example Arr2[2];② additions and deletions:Deleta Arr[n]Delete the n+1 value of the array, but the array length is the same, the value of the corresponding position is undefinedArr3.push (value);The array finally adds a value of arr3[arr3.length]=7;Arr3.unshift (value);The 0th bit of the array inserts a value and the rest of the digits are postponedArr3.pop ();Delete the last array, unlike delete, the array length is reduced by one after the pop is executed. Equivalent to Arr3.length-=1Arr3.shift (); Delete array No. 0 bit, array length minus one4. Other common methods in the array:①Join ("delimiter")method, separating the array with the specified delimiter and converting it to a string. When the argument is empty, the default is separated by commas ②concat ();(the original array will not be changed) concatenate the array with the values of multiple arrays [1,2].concat ([3,4],[5,6]) =[1,2,3,4,5,6]; When connecting, the brackets are removed at most [1,2].concat ([1,2,[3,4]]) =[ 1,2,1,2,[3,4]]; multi-layered brackets, in the form of a two-dimensional array of ③push array Last added a number, Unshift array begins to add a number, "returns the array of the latest length" pop delete the last number of the array; Shift: Delete array First "return deleted value" Call the above method, the original array is changed ④reverse (); array inversion. In reverse order. (the original array is changed) ⑤Slice (begin,end); [The original array will not be altered] to intercept a part of the array into a new array, passing a parameter to start the index by default, starting from the current subscript to intercept to the last; pass two parameters, intercept from begin to end interval, left closed right open, contain begin, without end argument can be negative, Negative one represents the last ⑥sort (function)"The original array will be changed" to sort the arrays, do not specify the sorting method, by default, the first ASCII value to arrange the incoming sort function, the default two parameters a.b, if the return value >0, then a>b; return <0, then a<b Arr3.sort (function (b) { return a-b;//in ascending order return b-a;//Descending order });⑦indexof (Value,index); returns the subscript position corresponding to the first value value in the array, returns -1LASTINDEXOF (Value,index) If not found, returns the subscript position corresponding to the last value value,------------ >>>> if the index parameter is not specified: The default is to query all elements of the array, and if you specify the index parameter, start with the current index and query backwards;5. Two-d arrays and sparse arrays "understanding"① sparse array: The array does not contain all indexes starting from 0 to length-1 (its length is greater than the actual number of elements); ② two-dimensional array: var ARR5 = [[1,2,3],[4,5,6],[7,8,9],[0,1,2]]; The equivalent of a matrix of four rows and three columns takes out a two-dimensional array element: arr[[column number], which can be traversed using nested loops6. Reference data types and basic data typesReference data type: When an array/object is assigned a value, the address of the original variable is assigned to the new variable. Two variables actually manipulate the same data, so modify one of the variables to change the base data type: When assigning a value, the value of the original variable is assigned to the new variable. Two variables belong to different memory space, modify one, do not interfere with each other 6. Built-in objects inJsBoolean classvar isTrue = true;//simple variable var isTrue1 = new Boolean (true);//A Boolean object Console.log (isTrue1);Number classNumber.min_value the maximum number of number.max_value that can be represented by the minimum numbernum.tostring () convert num to string?str3=num.tofixed (n); Leave n decimal places, rounding, and converting to strings?.valueOf () returns the base numeric value of the number object?Num.tolocalestring () converts numbers into strings in the order of local formatting. It is usually three groups with commas. Toprecision (n) formats the number as a specified length, n= does not contain all digits of the decimal point and var num=1;//number type var num1=new number (1);//object type var str = Num.tostring ();//string type var str2=num.tolocalestring (); var str3=num.tofixed (2); Console.log (Number.MAX_VALUE) Num.valueof ();String class Strings1. Properties:. toLowerCase (); All characters are converted to lowercase. . toUpperCase (); Convert all characters to uppercase. . charAt (n); intercepts the nth character in a string: indexOf ("Query substring", index), the index of the first substring starting at index, not found, returns-1. SUBSTRING (begin,end); intercepts substrings, writes only one parameter, starting from begin to the end, writes two parameters from begin to end, left closed right. Replace ("old", "new"); Replace the first old in the string with new; The first argument can be a string, or it can be a regular expression (the normal string will only match the first one, and the regular expression is differentiated according to the case). Split (""); divides a string into an array by specifying a delimiter. Passing in "" empty string will put a single character into the arrayvar str = "I old A shuaige"; var Xiaoxie = Str.tolowercase (); Str.charat (0); Str.indexof (); str.substring (); var rep= Str.replace ("old", "new"); Console.log (rep);Date Class1. New date (); Get the current time; new Date ("2017,4,4,14:58:12"); set the specified time 2. Common methods:. getFullYear (): Gets the 4-bit year. GetMonth (); Gets the month 0~11. GetDate (); Gets the day of the one month 1--31.getday (); Gets the day of the week. 0--6.gethours () returns the hour of the date object (0 ~ 1) 2 3.getMinutes () returns the minute of the Date object (0 ~ min) 1 2 3.getSeconds () returns the number of seconds of the date object (0 ~ 59) ) 7. Custom objects inJs1. Basic concept:
① object: An object contains a collection of unordered properties and methods;
② Keyboard pair: The data in the object isKeyboard PairIn the form of a key value;
③ Property: A series of variables that describe the characteristics of an object. "Variables in an object"
④ method: A series of methods that describe the behavior of an object. "Functions in Objects"
2, the object of the declaration:
① literal declaration:
var obj = {
Key1:value1,//Properties
Key2:value2,
Func:function () {}//method
}
A key in the =-= object, which can be any data type, but is generally used as a common variable name ("" is not required).
The value in the =-= object can be any data type, but the string must be "" wrapped
=-= multiple sets of key-value pairs are separated by commas, and key-value pairs are separated by the keys and values in English: delimited
New keyword:
var liSi = new Object ();
Lisi.name = "John Doe";
Lisi.say = function () {
Console.log ("I am:" +this.name);
}
3. Read and Write properties and methods in objects
①. Operator:
Object inside: this. Property name this. Method Name ()
External object: Object name. property name Object name. Method Name ()
② via ["Key"] Call: Object name ["Property name]" ()
>>> If the key contains special characters, you cannot use the ① method, you must use the second type;
>>> object, write the variable name directly, the default is to call the global variable, if you need to call the object itself property, you need to pass the This keyword
③ deleting an object's properties and methods: Delete Object name. Property/Method Name 8. Regular Expressions1. The regular expression consists of two parts:①-defined regular expression rule ② regular expression pattern (g/i/m)2. Declarations of regular Expressions① literal declaration:var reg=/expression rule/expression pattern/white/g②new keyword declaration:var reg=new RegExp ("Expression rule", "expression pattern") var reg=new RegExp ("White", "G")3. Common methods of regular expressions:. Text (): detects if a string matches a regular pattern, returns true, false;4. Common patterns of regular expressions:G Global match, without G default non-global match, match only the first qualifying string (example: "www". Replace (/w/, "#") >>> #ww)I ignores case. Do not add I default to match caseExample: "AAA". Replace (/a/, "#") >>>a#a "AAA". Replace (/a/i, "#") >>> #Aam matches multi-line mode. Multiple lines of string are displayed, each line has an opening endingExample "ABC" #bcabc ". Replace (/^a/g," # ") >>>abc" "abc" #bcabc ". Replace (/^A/GM," # ") >>> #bc"Below is an email with a regular judgment:
var email=document.getelementbyid ("Mail"). Value;             var reg3=/^\w+\@[a-za-z0-9]{2}[a-za-z0-9]?\. [A-z] {2} [a-z]?$/            if(reg3.test (email)) {                Console.log ("right");            }             Else {                Console.log ("wrong");            }

OK, I believe this will be, write some of the original JS to achieve the function has no problem! Personal feeling the most important thing is to learn to take the node, can take the thought of the node, what things are say ...

JavaScript Essentials Summary--the most Important

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.