Basic JavaScript syntax

var a = [1, 2, 5]; for(var k in a){ console.log(k); } for(var m of a){console.log(m); // m is the value of the current element} vm215:3 0 vm215:3 1 vm215:3 2 vm215:6 1 vm215:6 2 vm215:6 5Copy the code

Variable declarations

  • varDeclare a variable that can be assigned an initial value.
  • letDeclares a block-scoped local variable that can be assigned an initial value.
  • constDeclares a block scoped read-only named constant.
  • The name of a variable is also called an identifier,It must start with a letter, underscore (_), or dollar sign ($), and is case sensitive.
  • If no initial value is assigned to a variable, the value defaults toundefined
  • Throw if used without declaring a variableReferenceErrorerror
  • When the variable value is zeroundefined, the Boolean environment asfalse
  • When the variable value is zeronull, the Boolean environment asfalse

The data type

  • Boolean Boolean values, true and false
  • Null is case sensitive
  • Undefined empty type. The value of the variable is undefined
  • Number Number type
  • String String type
  • Symbol (new in ES6) represents a unique and immutable data

literal

  • The literal is just a way of saying how do I express this value
  • The variables assigned to the right are all literals
  • Array literals
  • Boolean literals
  • Floating-point number area
  • Object literals
  • Integer literals
  • Regular literal
  • String literals

The global variable

Code:

// ES5

var a = 'web';

window.a; // 'web'

// ES6

let b = 'web';

window.b; // undefined
Copy the code

annotation

Code:

// Single-line comment /* multi-line comment */Copy the code

Variable scope

  • Global variables: that is, declared outside the function and accessible everywhere in the current document
  • Local traversal: that is, declared inside a function and accessible only within the current function

Code:

// ES5 and previous console.log(a); // undefined var a = 1; console.log(a); // 1 // ES6 start console.log(b); // Uncaught ReferenceError: b1 is not defined let b = 2; console.log(b); / / 2Copy the code

There are two ways to declare a function

Code:

// function declaration f(); // 'web' function(){ console.log('web'); };Copy the code
// function expression g(); // Uncaught TypeError: g is not a function var g = function(){console.log('web'); }Copy the code

constant

  • Use const to declare a read-only constant
  • Const variables cannot be modified directly, but objects and arrays are not protected and can be modified
  1. A completejavascriptThe implementation consists of three parts: the coreECMAScriptDocument Object ModelDOMBrowser object modelBOM.
  2. JavaScriptIs a literal scripting language, a dynamically typed, weakly typed, prototype-based language with built-in typing support.
  3. JavaScriptFeatures: an interpretative scripting language, mainly used to add interactive behavior to HTML pages, can be directly embedded in HTML pages, but written as a separate JS file is conducive to the separation of structure and behavior.
  4. Cross-platform feature, with the support of most browsers, can run on a variety of platforms.
  5. JavaScriptSyntax differences: case sensitive, variables are weakly typed, ending semicolons are optional, interpretation andJava, C and PHPAnnotations are the same in the language, and braces represent blocks of code.

The contents of the example {} represent a code block

Code:

if(test1=="red") {
    test1 = "blue";
    alert(test1);
}
Copy the code

JavaScript keywords:

break,else,new,var
case,finally,return,void
catch,for,switch,while
continue,function,this,with
default,if,throw
delete,in,try
do,instanceof,typeof
Copy the code

JavaScriptThe variables of

In javascript, variables are containers that store information and have two types of values, the original value and the reference value.

  1. JavaScriptThe primitive type of, i.eUndefined.Null.Boolean.NumberandStringType.
  2. stringStringisJavaScriptThe basic data type of.
  3. Data type indicates the type of data,JavaScriptEvery value in a language belongs to a certain data type.
  4. JavaScriptThere are two types of data types: value types (raw values) and reference data types (reference values).
  5. Value types: string, number, Boolean, null, undefined undefined, symbol for ES6 introduced a new primitive data type, representing unique values.
  6. Reference data types: object, array array, function.
  7. JavaScriptprovidetypeofThe operator is used to determine whether a value is in a range of a type.
  8. UndefinedThe type has only one value, i.eundefined.
  9. When a declared variable is not initialized, the default value of the variable isundefined.
  10. NullType has only one valuenullAnd the valueundefinedStudent: Actually slave valuenullStudent: Derived, soJavaScriptLet’s define them as equal.
  11. nullwithundefinedIndicates that the two values are equal, but have different meanings.
  12. undefinedIs the value assigned to a variable that was declared but not initialized,nullRepresents an object that does not yet exist.

Code:

console.log( null == undefined); // true
Copy the code
  1. BooleanThe two values of type aretrueandfalse.
  2. NumberType. All mathematical operations return the result in decimal.
  3. Number.MAX_VVALUEandNumber.MIN_VALUEThey defineNumberThe outer boundary of the set of values.
  4. If the numeric result generated is greater thanNumber.MAX_VALUEIs given a valueNumber.POSITIVE_INFINITYIs no longer availableNumberValue. The generated value is less thanNumber.MIN_VALUEWill be assigned a valueNumber.NEGATIVE_INFINITYIs no longer availableNumberValue.
  5. There’s a value for infinityInfinity.
  6. Number.POSITIVE_INFINITYThe value ofInfinity.Number.NEGATIVE_INFINITYThe value of-Infinity.

Use the isFinite() method to determine if the parameter value isFinite.

  1. specialNaNIs not a number. And just like infinity,NaNNor can it be used in arithmetic calculations. Pay attention to,NaNNot equal to itself.

Example:

console.log(NaN == NaN) // false
console.log(isNaN("66")); // false
Copy the code
  1. StringType, which is the only primitive type without fixed size, string literals are declared in double or single quotation marks.

Type judgment

  1. typeofOperator used to get the type of a variable or expression.

The return value:

Undefined, the variable is undefined Boolean, the variable is Boolean number, the variable is string of type number, the variable is object of type string, the variable is a reference type or NullCopy the code

Example:

console.log(typeof 12); // number
Copy the code

The Typeof operator returns Object on a null value.

  1. instanceofOperator to determine which type a reference type belongs to.

Example:

<script> var a = new Array(); If (a instanceof Array) {console.log('a is an Array type '); }else{console.log('a is not an array type '); } </script>Copy the code

Type conversion

  1. NumberVariable, converts the variable to a numeric type.
  2. StringVariable, which is converted to a string type.
  3. BooleanVariable that converts a variable to a Boolean value type.
  4. parseFloatVariable to convert a variable to a floating point type.
  5. parseIntVariable, to convert the variable to an integer type.

The operator

  1. Operators: assignment operators, arithmetic operators, comparison operators, logical operators, unary operators, binary operators, ternary operators.
The name of the The operator meaning
The assignment x = y x = y
Add the assignment x += y x = x + y
Subtraction assignment x -= y x = x - y
Multiplication assignment x *= y x = x * y
Divide the assignment x /= y x = x / y
For the assignment x %= y x = x % y
Exponentiation assignment x **= y x = x ** y
Left shift assignment x <<= y x = x << y
Right shift assignment x >>= y x = x >> y
Unsigned right shift assignment x >>>= y x = x >>> y
Bitwise and assignment x &= y x = x & y
Xor assignment by bit x ^= y x = x ^ y

Example:

The assignment operators have the symbol = arithmetic operators: +, -, *, /, % Comparison operators: >, >=, <, <=,! =, ==, ==,! = = logical operators: &&, logic and expression before and after all to true to return true | |, logic or, said before and after expression returns true as long as there is a true! If the expression is true, false is returned; otherwise, vice versa.Copy the code
  1. ++Self-growing, incrementing itself by 1 each time it executes,--Self-subtracting. Each time it is executed, it subtracts by 1.
  2. i++The value evaluates to an external expression and then increments its own value by 1.
  3. ++iI increments itself by 1 before participating in the external expression.
  4. + =.a+=3Is equal to thea=a+3. Similarly.
  5. The expression of a ternary operator is of the form: condition? Is: false
  6. Operator precedence: arithmetic operator > comparison operator > logical operator > assignment operator.
  • Arithmetic operator
  • Comparison operator
  • Logical operator
  • The assignment operator

Branch loop

  1. if-elseConditional statement
  2. switch-caseSelect statement
  3. forLooping statements
  4. for-inTraversal statements
  5. whileLooping statements
  6. do-whileLooping statements

Example:

If (condition 1) {code executed when condition 1 is true}else if(condition 2){code executed when condition 2 is true}else{code executed when neither condition 1 nor condition 2 is true}Copy the code

Example:

Switch (n){case1: execute code block 1 break; Case2: execute code block 2 break; default: ... }Copy the code

Example:

For (statements 1; Statements 2; Statement 3){executed code block}Copy the code
  1. continueRepresents passing the current loop and continuing the next loop
  2. breakThe end of the loop

traverse

  1. for inStatement loop over properties of an object. Used of composite types such as objects, arrays, etc., to iterate over properties and methods.

Example:

For (key in object) {code block}Copy the code
  1. whileIf the expression is true, the loop can be entered.

Example:

While (expression){code block}Copy the code
  1. do-while

Example:

Do {code}while(expression)Copy the code

An array of

Array properties and methods:

methods instructions
concat() Joins two or more arrays and returns the result
join() Puts all the elements of an array into a string, separated by the specified delimiter
pop() Removes and returns the last element of the array
push() Adds one or more elements to the end of the array and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes and returns the first element of the array
slice() Returns the selected element from an existing array
sort() Sort the elements of an array
splice() Removes the element and adds a new element to the array
toSource() Returns the source code for this object
toString() Converts an array to a string and returns the result
toLocalString() Converts an array to a local array and returns the result
unshift() Adds one or more elements to the beginning of the array and returns the new length
valueOf() Returns the original value of an array object
indexOf() Searches the array for the specified element and returns the first matching index
lastIndexOf() Searches the array for the specified element and returns the last matching index

concat()

Joins two or more arrays and returns a new array.

Grammar:

arr.concat(a1, a2, ... , an)Copy the code

Parameters:

  1. arr: Target array
  2. a1,a2,... ,an: Elements to be merged

join()

Concatenates the elements of two or more arrays using the specified delimiter, returning a string.

To define an array

  1. usenewKeyword to create aarrayObject, you can create an array space in memory to add elements.
  2. usenewKeyword to create aarrayObject and assign n initial values to the array.
  3. Don’t have tonewDirect use,[]Declares an array that can be initialized directly.

An array of operating

  1. Add elements
  2. Delete elements, pop, Shift, splice.
  3. Through the array
  4. Insert elements, unshift method, splice method insert.
  5. Merge array
  6. Array to string
  7. Array elements in reverse order
  • popMethod, which strips the element from the array and returns it.
  • shiftMethod to remove the element from the header and return.
  • spliceMethod to remove the specified element from the specified location.
  • unshiftMethod, insert from the head.
  • spliceInserts a specified number of elements from a specified location.
  • concatThe concatenate () method joins multiple arrays into an array.
  • joinMethod combines the elements of an array into a string that is concatenated with the specified delimiter.
  • reverseThe reorder () method reverses the order of the elements in an array and changes the original array without creating a new one.
  • sortMethod to automatically sort the elements of an array according to certain rules (the default is ASCII character order).

Pop () and push ()

  1. Pop (): Removes and returns the last element of the array, changing the original array.
  2. Push (item): Adds one or more elements to the end of the array, changing the array and returning the new array length.

The shift () and the unshift ()

  1. Shift (): Removes and returns the first element of the array, changing the original array.
  2. Unshift (item): Adds one or more elements to the array header, alters the array, and returns the new array length.

Example:

let arr = [1, 2, 3, 5, 6];
let a1 = arr.slice(2);    // [3, 5, 6]
let a2 = arr.slice(2,3);  // [3]

let arr = [1, 2, 3, 4];
let a = arr.splice(1, 2, "web", "a");
// a =>  [2, 3]
// arr =>  [1, "web", "a", 4]
Copy the code

forEach()

Code:

Let a = hc-positie [1]; a.forEach(function(val, index, arr){ arr[index] = val * 2 }) a ; // [2, 6, 10, 14]Copy the code

Code:

Arr.every (callback) tests whether all elements of the array pass the test of the specified function. Some () tests whether some elements in the array pass the test implemented by the provided function.Copy the code

filter()

Example:

let a = [1, "", "aa", 2, 6]; let res = a.filter(function(val, index, arr){ return typeof val == "number"; }) res; / / [1, 2, 6]Copy the code

map()

Execute this method on each element and return an array after execution.

Example:

let a = [1, 3, 5]; let b = a.map(function(val, index, arr){ return val + 1; }) b; / / (2, 4, 6]Copy the code

Extended operator

Extend operator usage (…)

Example:

console.log(... [1, 2, 3)); // 1 2 3 console.log(1, ... [2, 3], 4); // 1, 2, 3, 4Copy the code
// let a1 = [1, 2]; let a2 = a1; a2[0] = 3; console.log(a1,a2); // let a1 = [1, 2]; let a2 = [...a1]; // let [...a2] = a1; // a2[0] = 3; console.log(a1,a2); / / [1, 2] [3, 2]Copy the code
let [a, ...b] = [1, 2, 3, 4]; // a => 1 b => [2,3,4] let [a,...b] = []; // a => undefined b => [] let [a, ...b] = ["abc"]; // a => "abc" b => []Copy the code

fill()

  1. Fills an array with the specified value
  2. Initializes an empty array and erases existing elements
  3. The second and third arguments to fill() specify where to start and end the fill
new Array(3).fill('a'); / / / 'a', 'a', 'a'] [1, 2, 3]. The fill (' a '); / / / 'a', 'a', 'a'] [1, 2, 3]. The fill (' a ', 1, 2); // [1, "a", 3]Copy the code

entries(),keys(),values()

  1. entries()Traversal of key and value pairs
  2. keys()Traversal of key names
  3. values()Iterate over key values.

includes()

  1. includes()Used to indicate whether the array contains a given value
  2. The second argument is the starting position, which defaults to 0, or the reciprocal position if negative, or reset to start at 0 if greater than the array length.

Code:

[1, 2, 3]. Includes (3, 3); / / false [1, 2, 3]. Includes (3, 4); / / false [1, 2, 3]. Includes (3, 1); / / true [1, 2, 3]. Includes (3, 4); // trueCopy the code

flat(),flatMap()

Example:

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
Copy the code
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]
Copy the code

grammar

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
Copy the code
var arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened arr1.flatMap(x => [[x * 2]]); [[2], [4], [6], [8]]Copy the code
let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]
Copy the code

Array.prototype.reduce()

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); Var total = [0, 1, 2, 3]. Reduce ((acc, cur) => ACC + cur, 0);Copy the code

grammar

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, InitialValue]) initialValue Is optional as the value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.Copy the code

String object properties

String object properties

attribute instructions
constructor A reference to the function that created the object
length Length of string
prototype Allows you to add properties and methods to objects

String object method

String object method

attribute instructions
anchor() Create an HTML anchor
big() Display strings in large font
blink() Displays a flash string
bold() Display strings in bold
charAt() Returns the character at the specified position
charCodeAt() Returns the Unicode encoding of the character at the specified position
concat() Connection string
fixed() Displays a string as typewriter text
fontcolor() Displays the string using the specified color
fontsize() Displays a string using the specified size
fromCharCode() Creates a string from the character encoding
indexOf() Checking strings
italics() Display strings in italics
lastIndexOf() Searches the string from back to front
link() Displays the string as a link
localeCompare() Compares two strings in a locally specific order
match() Find a match for one or more regular expressions
replace() Replaces the substring that matches the regular expression
search() Retrieves the value that matches the regular expression
slice() Extracts a fragment of a string and returns the extracted portion in a new string
small() Display strings in small font size
split() Splits a string into an array of strings
strike() Displays a string using a stripper
sub() Displays strings as subscripts
substr() Extracts a specified number of characters from the initial index number in the string
substring() Extracts the character between two specified index numbers in a string
sup() Displays strings as superscripts
toLocaleLowerCase() Converts a string to lowercase
toLocaleUpperCase() Converts a string to uppercase
toLowerCase() Converts a string to lowercase
toUpperCase() Converts a string to uppercase
toString() Return string
valueOf() Returns the original value of a string object
toSource() Represents the source code of the object

String search

IndexOf(), lastIndexOf(), Search () and match().

  1. indexOf().IndexOf (search term, starting index position)If the second parameter is not written, the search starts from 0 by default.indexOf()Retrieves the position where the specified string value first appears in the string.
  2. lastIndexOf().LastIndexOf (search term, starting index position), returns the last occurrence of a specified substring value.
  3. search(), the syntax is string,Search (search word)Or a stringSearch (regular expression).
  4. match()The syntax is a string.match()You can retrieve a specified value within a string or find a match for one or more regular expressions. Returns if no match is foundnull. If there is a match, it returns an array, and the 0th element of the array holds the match text.

String interception

3 string interception methods: Substring (),slice(),substr()

  1. substring(), the syntax is string,Substring (start interception, end interception).substring()Is a common string interception method that takes two arguments, not negative values, and returns a new string.
  2. slice(), the syntax is string,Slice (intercept start position, intercept end position).slice()The argument can be negative, or if negative, the position of the argument from the end of the string.- 1Is the last character of a string.
  3. substr().Substr (intercepts the start position, length)Extracts a specified number of characters from the subscript at the beginning of interception in a string. Returns a string truncated from the end of the string if the truncated position is negative.

String substitution

Replace (), replace(regular expression/string to be replaced, substring to be replaced).

String cutting

Split () is used to split a string into an array of strings, syntax string. Split (substring used to split, returns the maximum length of the array), returns the maximum length of the array normally not set.

The JS event has three phases

Flow of events:

  1. Event bubbling flow
  2. Event capture flow

There are three phases in the event processing: capture phase, target phase, and bubbling Phase The event flow consists of the capture phase, the target phase, and the event bubbling phase.

  • Capture, events are received by page elements, level by level, down to specific elements
  • The goal, the concrete element itself
  • Bubbling, the element itself, up to the page element
  1. Event capture. When event capture is used, the parent element fires first, followed by the child element.
  2. Event bubble. When an event bubble is used, the child element fires first, followed by the parent element.

Event bubbling and event capture

  1. Event flow is generated when an event occurs
  2. DOMFlow of events:DOMStructure is a tree structure. When an HTML element generates an event, the event is propagated in a specific order between the element node and the root node, and all the nodes that the path passes through receive the event.
  3. There are two types of event flow sequence: event bubbling and event capture.

Event triggering mode

Code:

addEventListener("click","doSomething","true")
Copy the code

The third parameter is true, indicating event capture, or false, indicating event bubbling.

<! DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8"> <title>Document</title> <style> html,body{ width:100%; height:100%; } </style> <script> window.onload=function(){ d1 = document.getElementById("d1"); d2 = document.getElementById("d2"); d3 = document.getElementById("d3"); D1.addeventlistener ("click",function(event){console.log("d1")},"true"); d2.addEventListener("click",function(event){ console.log("d2") },"true") d3.addEventListener("click",function(event){ console.log("d3") },"true") } </script> </head> <body> <div id="d1" style="background: #0000ff; width: 500px; height: 500px"> <div id="d2" style="background: #00ff00; width: 400px; height: 400px"> <div id="d3" style="background: #ff0000; width: 200px; height: 200px"> </div> </div> </div> </body> </html>Copy the code

AddEventListener page, click to jump to: adDeventListener.html

Event delegation

A response event delegates to another element.

< ul id = "BTN" > < li id = "btn1" > button 1 < / li > < li id = "btn2" > button 2 < / li > < li id = "btn3" > button 3 < / li > < / ul > var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); var btn3 = document.getElementById('btn3'); MyAddFun (btn1, 'click', function(event){alert('1 click'); }); Webbtn. myAddFun(btn2, 'click', function(event){alert('2 click'); }); Webbtn. myAddFun(btn3, 'click', function(event){alert('3 click'); });Copy the code

Add an event handler to do the event delegate

var btn = document.getElementById('btn'); webbtn.myAddFun(btn, 'click', function(event){ event = webbtn.getMyEvent(event); var target = webbtn.getMyTarget(event); Switch (target.id){case "btn1": alert('1 click '); break; Case "btn2": alert('2 click '); break; Case "btn3": alert('3 click '); break; }});Copy the code

Keyboard events

Keyboard events are the worlds triggered by keyboard actions.

Keyboard events:

methods instructions
keydown Triggered when the user presses any key on the keyboard. If you hold it, it will trigger repeatedly
keypress Triggered when the user presses a character key on the keyboard. If you hold it, it will trigger repeatedly
keyup Triggered when the user releases a key on the keyboard

Mouse drag effect

Mouse binding onMousedown (), onMousemove (), onMouseup () events.

Mouse web page, click to jump to: mouse.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>mouse</title> <style> html,body{ width: 100%; height: 100%; } #dd { width: 120px; height: 120px; background: #00ff00; position: absolute; } </style> <script> var dd; var mflag = false; function ondown() { dd = document.getElementById('dd'); mflag = true; } function onmove(e){ if(mflag) { dd.style.left = e.clientX - 60 + "px"; dd.style.top = e.clientY - 60 + "px"; } } function onup() { mflag = false; } </script> </head> <body onmousemove="onmove(event)"> <div id="dd" onmousedown="ondown()" onmouseup="onup()" style="left: 80px; top: 120px;" </body> </html>Copy the code

Mouse events

Mouse events:

methods instructions
click The user clicks the left mouse button or pressesEnterKey trigger
dbclick The user double-clicks the mouse
mousedown Triggered when the user presses any mouse button
mouseenter Triggered when the mouse cursor moves within an element for the first time from outside the element
mouseleave Triggered when the cursor above the element moves outside the element’s range, without bubbling
mousemove Triggered when the cursor moves continuously inside the element
mouseover The user pointer is outside one element and then fired when the user moves within the boundary of another element for the first time
mouseout Triggered when the user moves the cursor over one element to another
mouseup Triggered when the user releases the mouse
mousewheel Triggered when the roller rolls

Example:

function web(e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
    console.log("x:"+mouseX + "," + "y:"+mouseY)
}

<body onclick="web(event)">
Copy the code
  1. Mouse hover isonmouseover
  2. Mouse away isonmouseout

Window events

Window events:

  1. load
  2. unload
  3. abort
  4. error
  5. select
  6. resize
  7. scroll

Load event, which means that when the page is fully loaded, the load event on the window will be triggered. Contains all external resources such as images, JS files, CSS files, etc.

Example:

window.onload=function(){}
Copy the code

Execute the function when the page is fully loaded.

Example:

<script>
 window.onload = function() {
     var mydiv = document.getElementById("mydiv");
     console.log(mydiv.innerText);
 }
</script>

<body>
 <div id="mydiv"></div>
</body>
Copy the code

Example:

function imgLoad() { myimg = document.getElementById("myimg"); Myimg.style. border = "9px solid $00ff00"; } <img id="myimg src="" onload="imgLoad()">Copy the code

The resize event

  1. Triggered when the browser window is adjusted to a new width or heightresizeEvents.

Example:

Document. Body. ClientWidth and document. Body. ClientHeight get the width and height of the window.

html,body {
    width: 100%;
    height: 100%;
}

<script>
 function winChange() {
     winWidth = document.body.clientWidth;
     winHeight = document.body.clientHeight;
 }
</script>

<body onresize="winChange()">
</body>
Copy the code

The ScROL event triggers the Scroll event when a document or browser window is scrolled

Example:

<script> function scrollChange() { srpos = document.getElementById("srpos"); srpos.innerText = document.documentElement.scrollTop; srpos.style.top = docuemnt.documentElement.scrollTop+"px"; } </script> <body onscroll="scrollChange()"> <div style="height:300%;" > <br/> <font id="srpos" style="position: relative; Top: 0px"> Scroll to 0px</font> </div> </body>Copy the code

“Event”

methods instructions
blur Triggered when an element loses focus, supported by all browsers
focus Triggered when an element is in focus, supported by all browsers

Example:

<script> var note; function myfocus(fname,notename) { note = document.getElementById(notename); Note. InnerText = fname+' Get focus '; } function myblur(fname,notename) { note = document.getElementById(notename); Note. InnerText = fname + 'lose focus '; } </script> <body> <form name="myform"> <input type="text" name="uname" onfocus="myfocus('uname','unote')" onblur="myblur('uname','unote')"/><font id="unote"></font> <br/> <input type="text" name="pwd" onfocus="myfocus('pwd','pnot')" onblur="myblur('pwd','pnote')"/><font id="pnote"></font> </form> </body>Copy the code

Events are introduced

Event method

methods instructions
onabort Image loading is interrupted
onblur Element out of focus
onchange The user changes the content of the domain
onclick Click an object
ondblclick Double-click an object
onerror An error occurred while loading a document or image
onfocus Element gets focus
onkeydown A key on a keyboard is pressed
onkeypress A keyboard key is pressed or held down
onkeyup A key on a keyboard was released
onload A page or image has been loaded
onmousedown A mouse button is pressed
onmousemove Mouse moved
onmouseout Move the mouse pointer away from an element
onmouseover The mouse is moved over an element
onmouseup A mouse button is released
onreset The reset button is clicked
onresize A window or frame is resized
onselect Text selected
onsubmit The submit button is clicked
onunload User Exit page

Window events

  1. loadThe event
  2. resizeThe event
  3. scrollThe event
  4. “Event”

Mouse events

  1. Gets the mouse click position
  2. Mouse hover and away
  3. The mouse to drag and drop

Keyboard event with event bubbling, get

JavaScript built-in objects

  1. windowobject
  2. documentobject
  3. locationobject
  4. navigatorobject
  5. screenobject
  6. historyobject

JavaScript DOM operations, including get node, get, set element attribute value, create, add node, delete node, attribute operations.

DOMobject

  1. When a web page is loaded, the browser creates a document object model of the page,Document Object Model, the document Object model belongs toBOMPart of, used forBOMThe core object indocumentPerform operations.
  2. html domThe model is constructed as a tree of objects.

DOMoperation

Method of obtaining nodes:

  1. The labelidAccess to:
document.getElementById(idName)
Copy the code
  1. The labelnameProperty fetch: Returns an array of elements
document.getElementsByName(name)
Copy the code
  1. Category Name get: Returns an array of elements
document.getElementsByClassName(className)
Copy the code
  1. Label name fetch: Returns an array of elements
document.getElementsByTagName(tagName)
Copy the code

Gets, sets the attribute value of the element

  1. getAttribute(attributeName)Method, // parentheses in and out of the input name, returns the property value of the corresponding property
  2. setAttribute(attributeName,attributeValue)Method, // Pass in the name of the property and the value set

Example:

<script> window.onload=function(){ mytable = document.getElementById('mytable'); / / get mytable winning signature for tr bytes point TRS = mytable. GetElementsByTagName (" tr "); len = trs.length; flag = true; for(i=0; i<len; i++){ if(flag){ trs[i].setAttribute('bgcolor','#cccccc'); flag = false; }else{ flag = true; } } ww = mytable.getAttribute('width'); } </script> <body> <table id="mytable' align='center' width="80%" border="1"> <tr bgcolor = "#cccccc"> <td>aaa</td> <td>bbb</td> <td>ccc</td> </tr> </table> </body>Copy the code

Create and add a node

  1. Create a node:

Code:

// Create a node: document.createElement("h1"); document.createTextNode(String); document.createAttribute("class");Copy the code
  1. Adding a node:

Code:

element.appendChild(Node);

element.insertBefore(newNode, existingNode);
Copy the code
  1. Remove nodes

Code:

element.removeChild(Node)
Copy the code

Attribute operations: Get the parent node of the current element, get the child node of the current element, get the sibling element of the current element, get the text of the current element, get the node type of the current node, set the style.

  • Gets the parent node of the current element

Code:

element.parentNode
Copy the code
  • Gets the child nodes of the current element

Code:

element.chlidren
Copy the code
  • Gets the sibling of the current element

Code:

element.nextElementSibling

element.previousElementSibling
Copy the code
  • Gets the text of the current element

Code:

element.innerHTML

element.innerText
Copy the code
  • Gets the node type of the current node

Code:

node.nodeType
Copy the code

BOM object

  1. BOMObjects, called built-in objects, are the browser object model, as wellJavaScriptIs an important part of.
  2. window-“document,location,navigator,screen,history
  3. windowObject represents a browser window
  4. window.innerHeightGets the internal height of the browser window,window.innerWidthGets the internal width of the browser window.
  5. document.documentElement.clientHeight.document.documentElement.clientWidth;document.body.clientHeight.document.body.clientWidth.
  6. Open a new window,window.open(url).
  7. Close the current window,window.close().
  8. Resize the current window,Window. ResizeTo (width, height)

The document object

Document attributes and methods:

Properties and methods instructions
document.bgColor Set the page background color
document.fgColor Set the foreground
document.linkColor Color of unclicked links
document.alinkCOlor Activate the color of the link
document.vlinkColor The color of the link that has been clicked
document.URL Sets the URL property to open another page in the same window
document.cookie Set or readcookie
document.write() Write content to the page dynamically
document.createElement(Tag) Create an HTML tag object
document.getElementById(ID) Get the specifiedidThe object of value
document.getElementsByName(Name) Get the specifiednameThe object of value
document.body Specifies the beginning and end of the document body
document.location.href Full url
document.location.reload() Refresh current page
document.location.reload(url) Open a new page

Location object

Location properties and methods:

Properties and methods instructions
location.href Displays the URL link of the current web page
location.port The port that displays the current web page link
location.reload() Refresh the current page

The navigator object

The Navigator object contains information about the browser

attribute instructions
appName Returns the name of the browser
appVersion The platform and version information of the browser is displayed
cookieEnabled Returns whether the specified browser is enabledcookieBoolean value
platform Return to the operating system platform where the browser is running

The screen object

  1. eachwindowThe object’sscreenAttributes all reference onescrrenObject.
  2. screenObject that holds information about displaying the browser screen.

Properties of the Screen object:

attribute instructions
availHeight Returns the height of the display screen
availWidth Returns the width of the display screen
bufferDepth Sets or returns the bit depth of the palette
Height Returns the height of the monitor screen
Width Returns the width of the monitor screen

The history object

  1. historyObject contains urls that the user has accessed.

Properties of the history object:

attribute instructions
history.length Returns the number of urls in the browser history list
history.back() loadinghistoryThe previous URL in the list
history.forward() loadinghistoryThe next URL in the list
history.go() loadinghistoryA specific page in the list

Built-in function

  1. String function
  2. The array functions
  3. Mathematical function
  4. Date function

Mathematical function

attribute instructions
ceil The smallest integer greater than or equal to the number, rounded up
floor The largest integer less than or equal to the number, rounded down
Min (Parameter 1, parameter 2) Return minimum value
Max (Parameter 1, parameter 2) Return maximum value
Pow (Parameter 1, parameter 2) Returns the value 1 to the value 2
random() Return random number
Round (number) rounded
SQRT (number) A square root

Date function

  • set: used to setDateObject’s date and time values.
  • get: Use to getDateObject’s date and time values.
  • to: used to returnDateObject in string format.
  • The parse and UTC: used to parseDateA string.
attribute instructions
getFullYear() Get the full year
getMonth() Get current month
getDate() Get current day
getDay() Gets the current day of the week
getTime() Get the current time (since 1970.1.1)
getHours() Gets the current hour
getMinutes() Get the current score
getSeconds() Gets the current number of seconds
toLocalDateString() Get the current date
toLocalTimeString() Get the current time
toLocalString() Gets the date and time
  1. Seconds/min: 0-59;
  2. Time: 0-23;
  3. Week: 0(Sunday) – 6(Saturday)
  4. Date: 1-31
  5. Month: 0(January) – 11(December)
  6. Year: number of years starting from 1900

Timer function

  1. setInterval()To call a function or evaluate an expression at the specified period.
  2. setTimeout()To call a function or evaluate an expression after the specified number of milliseconds.
  3. The difference between:setTimeout()It only runs once,setInterval()It runs in a loop.

function

  1. Function is composed of function name, parameter, function body and return value.

Code:

Function name (parameter){function body return value}Copy the code
  1. There are three types of function declaration: declaration by function name, which can be executed when the program is called; By assigning an anonymous function to a variable, the call can be executed; Declare by new, no call, execute directly.

Code:

function web1 () { document.write("1"); } web1(); var web2 = function(){ document.write("2") } web2(); Var web3 = new function(document.write("3")); var web3 = new function(document.write("3"));Copy the code
  1. The function returns a value. The function may or may not return a value after execution.
  2. Function call: value call, address call, function call.

The closure function

  • Internal functions can only be accessed in external functions
  • Inner functions form closures
  • You can access parameters and variables of external functions
  • External functions cannot use the arguments and variables of the inner function
  • Closures provide a measure of security for variables of internal functions

In JS, when a function is defined in another function, it can access the member of the parent function, and the internal function is called closed function.

Closure is short for lexical closure, a function that refers to a free variable.

Closure function features:

  1. Closures, as data paired with functions, are active during function execution.
  2. After the closure finishes running, the final data state during the run is maintained
  3. Lexical Closure (English: Closure), also called Lexical Closure or function closures
  4. A closure is implemented as a structure that stores a function (usually its entry address) and an associated environment (equivalent to a symbol lookup table).
  5. Lexical scope

Code:

function init() { var name = "web"; // name is a local variable created by init. Function displayName() {// displayName() is an inner function, a closure alert(name); // use a variable declared in the parent function} displayName(); } init();Copy the code

Init () creates a local variable name and a function called displayName().

DisplayName () is an internal function defined in init() and is only available inside the init() function.

DisplayName () does not have its own local variable. However, because it can access variables of external functions, displayName() can use the variable name declared in the parent function init().

The alert() statement inside the displayName() function successfully displays the value of the variable name declared in its parent function.

This example of lexical scope describes how the parser resolves variable names in nested functions.

A lexical scope determines where a variable is available based on where it is declared in the source code. Nested functions can access variables declared outside their scope.

A closure is an expression (usually a function) that has many variables and the environment to which they are bound, and thus these variables are part of that expression.

All functions in JavaScript are closures. But in general, nested functions produce more powerful closures, and most of the time what we call “closures”.

The role of closures

After A executes and returns, closures prevent Javascript’s garbage collection mechanism, the GC, from reclaiming a’s resources because a’s internal function, B, depends on variables in A for execution.

  1. Excution Context
  2. Call Object
  3. Scope (scope)
  4. Scope chain

Timers and closures

The code is as follows:

for(var i = 0 ; i<10; i++){ setTimeout(function(){ console.log(i); }, 100); }Copy the code

I’m going to return 10 tens.

Solution:

  1. Use the new LETS in ES6.
  2. Using closures
for(var i = 0; i<10 ; i++){
    (function(i){
        setTimeout(function(){
            console.log(i);
        }, i*100);
    })(i);
}
Copy the code

Before ES6, using var to declare a variable increased the problem:

for(var i = 0 ; i<10; i++) { console.log(i) }; console.log(i); // Variable promotion returns 10Copy the code

object

  1. There are two ways to declare an object: throughnew Object()and{}The implementation.

Example:

// 1
var Person = function(id,name){
    this.id = di;
    this.name = name;
}
var user1 = new Person(1,"web");

// 2
var web1 = {id:1,name:"web"};
var web2 = Object.create({id:2,name:"web"});
Copy the code

Regular expressions are too difficult

Creating regular expressions

Use a regular expression literal:

let reg = /ab+c/;
let reg = /^[a-zA-z]/gi;
Copy the code
  1. Can’t remember, can’t remember, can’t remember.
  2. A regular expression is a text pattern consisting of ordinary characters and special characters.
  3. Regular expressions contain cards, positioners, qualifiers, escapes, and so on.
  4. There are two methods in regular expressions: string method and regular object method.

String method

attribute instructions
search() Retrieves the value that matches the regular expression
match() Find a match for one or more regular expressions
replace() Replace string with regular expression
split() Splits a string into an array of strings

Regular object method

RegExp object method

attribute instructions
test() Used to test whether a string matches a pattern
exec() This method is used to retrieve a match for a regular expression in a string, and this function returns an array
[a-z] Matches any character from a to Z in lowercase lettersCopy the code
[a-z] matches any character from A to Z in uppercase lettersCopy the code
[0-9] matches any character from the digits 0 through 9, equal to \dCopy the code
[0-9a-z] Matches any character from digits 0 to 9 or lowercase letters a to Z.Copy the code
[0-9a-za-z] matches any of the digits 0 to 9 or lowercase a to Z or uppercase A to ZCopy the code
[abcd] Matches any character in abcdCopy the code
[^a-z] matches any character except lowercase letters a to ZCopy the code
[^0-9] matches any character except the digits 0 through 9Copy the code
[^abcd] Matches any character except abcdCopy the code

Metacharacters are characters that have special meanings:

. Finds single characters, except newlines and line terminators.Copy the code
\w Finds word characters.Copy the code
\W Finds non-word characters.Copy the code
\d Find a number.Copy the code
\D Finds non-numeric characters.Copy the code
\s Finds whitespace characters. \S Finds non-whitespace characters.Copy the code
\0 Find the NUL character. \n Find a newline character. \f Find the page feed character. \r Find carriage return. \t Find TAB characters. \v Finds vertical tabs.Copy the code
\ XXX finds the character specified in the octal number XXX. \ XDD finds characters specified in hexadecimal number dd. \uxxxx finds Unicode characters specified in the hexadecimal number XXXX.Copy the code

quantifiers

Measure words to describe

quantifiers describe
n+ At least one string of n.
n* A string of zero or more n’s.
n? A string of zero or one n characters.
n{X} A string of X n sequences.
n{X,Y} A sequence of X to Y n strings.
n{X,} A string of at least X sequences of n.
n$ Matches any string ending in n.
^n Matches any string starting with n.
? =n Matches any string immediately followed by the specified string n.
? ! n Matches any string that is not immediately followed by the specified string n.
A locator can fix a regular expression at the beginning or end of a line, or create a regular expression that appears only within a word or at the beginning or end of a word.Copy the code
^ Matches the start of the input stringCopy the code
$matches the end of the input stringCopy the code
\b Matches a word boundaryCopy the code
\B Matches non-word boundariesCopy the code
/^[\d]{4}-[\d]{1,2}-[\d]{1,2}${1,2}$]/ date characterCopy the code
Escape character The escape character (backslash \) is used to escapeCopy the code

New RegExp(STR [, attr]) takes two arguments. STR is a string specifying the regular expression matching rule, and attr is optional, representing the matching pattern. The values include G (global matching), I (case-sensitive matching), and M (multi-line matching).

Expressions: g, I,m G means that the global pattern is applied to all strings, instead of stopping at the first match. I means case-insensitive pattern. M means multi-line patternCopy the code
The modifier describe
i Performs case-insensitive matching.
g Perform global matching.
m Perform multi-line matching.

The arguments object

The actual arguments to the function are stored in an array-like object called Arguments, which accesses the arguments by index:

var a = arguments[i]
Copy the code
  1. usearguments.lengthTo get the actual number of arguments passed in
  2. argumentsObject to get each parameter

The text box loses the focus event and gains the focus event

OnBlur: This event occurs when the input focus is lost

OnFocus: This file is generated when the input gets focus

Onchange: This event is generated when the literal value changes

Onselect: This file is generated when the text is highlighted

The top three periods of memory

  1. Two hours before bedtime
  2. An hour after waking up
  3. 8 to 10 o ‘clock in the morning