Basic JavaScript Syntax
Website update: http://www.dadaqianduan.cn/#/%E5%89%8D%E7%AB%AF%E5%A4%8D%E7%9B%98%E8%AF%BE/JavaScript%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A 1
var a = [1, 2, 5];
for(var k in a){
console.log(k); K is the subscript of the current element
}
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 5
Copy the code
Variable declarations
var
Declare a variable that can be assigned an initial value.let
Declares a block-scoped local variable that can be assigned an initial value.const
Declares a block-scoped read-only named constant.- The name of a variable is also called an identifier,
Must start with a letter, underscore (_), or dollar sign ($) and be case sensitive
. - If no initial value is assigned to the variable, the default value is
undefined
- Thrown if a variable is not declared and used directly
ReferenceError
error - When the variable value is
undefined
, the Boolean value environment asfalse
- When the variable value is
null
, the Boolean value environment asfalse
The data type
- Boolean Boolean values, true and false
- Null is case sensitive
- Undefined is an empty type. The value of undefined variables
- Number Numeric type
- String String type
- Symbol (added in ES6) represents a unique and immutable data
literal
- Literals are used to say how do I express this value
- The right hand side of a variable assignment is a literal
- Array literals
- Boolean literals
- Floating point number surface quantity
- Object literals
- Integer literal
- 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 comments
/ *
Multiline comment
* /
Copy the code
Variable scope
- Global variables: those declared outside of a function are accessible anywhere in the current document
- Local traversal: declared inside a function and accessible only within the current function
Code:
// ES5 and before
console.log(a); // undefined
var a = 1;
console.log(a); / / 1
/ / start ES6
console.log(b); // Uncaught ReferenceError: b1 is not defined
let b = 2;
console.log(b); / / 2
Copy the code
There are two ways to declare a function
Code:
// Declare the function
f(); // 'web'
function(){
console.log('web');
};
Copy the code
// Function expression
g(); // Uncaught TypeError: g is not a function
Var g = function(){var g = function()
console.log('web');
}
Copy the code
constant
- Use const to declare a read-only constant
- Variables declared as const cannot be modified directly, but objects and arrays can be modified without protection
- A complete
javascript
The implementation consists of three parts: the coreECMAScript
, document Object modelDOM
, browser object modelBOM
. JavaScript
Is a literal scripting language. It is a dynamically typed, weakly typed, prototype-based language with built-in support for types.JavaScript
Features: An interpreted scripting language for adding interactive behavior to HTML pages, which can be embedded directly in HTML pages, but written as separate JS files to help separate structure and behavior.- Cross-platform feature, with the support of most browsers, can run on multiple platforms.
JavaScript
Syntax differences: case sensitive, variables are weakly typed, ending semicolons are optional, interpretation andJava, C and PHP
Annotations are the same in languages, with braces representing blocks of code.
The example {} contains content that represents a block of code
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
JavaScript
The variables of
In javascript, variables are containers that store information, and there are two types of values for variables: raw values and reference values.
JavaScript
Of the original type, i.eUndefined
.Null
.Boolean
.Number
andString
Type.- string
String
isJavaScript
The basic data type of. - Data type represents the type of data,
JavaScript
Every value in a language belongs to a data type. JavaScript
There are two types of data types: value types (raw values) and reference data types (reference values).- Value type: string, number, Boolean, null, undefined, symbol is a new raw data type introduced by ES6, representing a unique value.
- Reference data types: object, array, function.
JavaScript
providetypeof
Operator to determine whether a value is within a range of a type.Undefined
The type has only one value, which isundefined
.- When the declared variable is uninitialized, the default value for the variable is
undefined
. Null
Type has only one value ofnull
And the valueundefined
Actually from the valuenull
Student: derived from soJavaScript
I’m going to define them as equal.null
withundefined
Indicates that the two values are equal but have different meanings.undefined
Is the value assigned to a variable when it is declared but not initialized,null
Represents an object that does not yet exist.
Code:
console.log( null == undefined); // true
Copy the code
Boolean
The two values of type aretrue
andfalse
.Number
Type, all mathematical operations return decimal results.Number.MAX_VVALUE
andNumber.MIN_VALUE
They defineNumber
The outer boundary of a set of values.- If the generated numeric result is greater than
Number.MAX_VALUE
Is given a valueNumber.POSITIVE_INFINITY
, indicating no longerNumber
Value. The value generated is less thanNumber.MIN_VALUE
Is given a valueNumber.NEGATIVE_INFINITY
, indicating no longerNumber
Value. - There is a value for infinity
Infinity
. Number.POSITIVE_INFINITY
The value ofInfinity
.Number.NEGATIVE_INFINITY
The value of-Infinity
.
Use the isFinite() method to determine if the parameter value isFinite.
- special
NaN
, is a non-number. Just like infinity,NaN
Nor can it be used in arithmetic calculations. Pay attention to,NaN
It’s not equal to itself.
Example:
console.log(NaN == NaN) // false
console.log(isNaN("66")); // false
Copy the code
String
Type is the only primitive type that does not have a fixed size. String literals are declared in either double or single quotation marks.
Type judgment
typeof
Operator that gets the type of a variable or expression.
The return value:
Undefined, the variable is undefined
Boolean. Variables are of type Boolean
Number, the variable is of type number
String, the variable is of type string
Object, the variable is a reference type or Null type
Copy the code
Example:
console.log(typeof 12); // number
Copy the code
The Typeof operator returns Object for a value of null.
instanceof
Operator 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
Number
Variable, convert the variable to a numeric type.String
Variable, convert the variable to a string type.Boolean
Variable, converts the variable to a Boolean value type.parseFloat
Variable to convert the variable to a floating point type.parseInt
Variable, convert the variable to an integer type.
The operator
- Operators: assignment operator, arithmetic operator, comparison operator, logical operator, unary operator, binary operator, ternary operator.
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 |
Bitwise XOR assignment | x ^= y |
x = x ^ y |
Example:
The symbol for the assignment operator is =
Arithmetic operators: +, -, *, /, %
Comparison operators: >, >=, <, <=,! =, ==, ===,! = =
Logical operators:
&& : returns true only if both sides of the expression are true
| |, logic or, said before and after expression as long as there is a true will return true
! Returns false if the expression is true, and vice versa.
Copy the code
++
Self-incrementing, incrementing itself by 1 for each execution,--
Decrement, minus 1 per execution.i++
, the value participates in the external expression and then increments its own value by 1.++i
, I first increments its own value by 1, and then participates in the operation of the external expression.+ =
.a+=3
Is equal to thea=a+3
. Same thing.- Ternary operators are expressed in the format of: conditional? Is: false
- Operator precedence: arithmetic operator > comparison operator > logical operator > assignment operator.
- Arithmetic operator
- Comparison operator
- Logical operator
- Assignment operator
Branch loop
if-else
Conditional statementswitch-case
Select statementfor
Looping statementsfor-in
Traversal statementswhile
Looping statementsdo-while
Looping statements
Example:
If (condition 1) {
The code to execute when condition 1 is true
}else if(condition 2){
The code to execute when condition 2 is true
}else{
The code that executes when neither condition 1 nor condition 2 is true
}
Copy the code
Example:
switch(n){
case1:
Execute block 1
break;
case2:
Execute block 2
break;
default:
.
}
Copy the code
Example:
For (statements 1; Statements 2; Statement 3) {
The block of code being executed
}
Copy the code
continue
To continue the next cycle over the current cyclebreak
It breaks out of the loop and ends the loop
traverse
for in
A statement that loops through the properties of an object. This statement is used to iterate through the properties and methods of a compound type, such as an object or an array.
Example:
For (key in object) {
The code block
}
Copy the code
while
If the expression is true, the loop can be entered.
Example:
While (expression){
The code block
}
Copy the code
do-while
Example:
do {
code
}while(expression)
Copy the code
An array of
Array properties and methods:
methods | instructions |
---|---|
concat() |
Concatenate two or more arrays and return 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() |
Invert the order of the elements in an array |
shift() |
Removes and returns the first element of the array |
slice() |
Returns the selected elements from an existing array |
sort() |
Sort the elements of an array |
splice() |
Remove elements and add new elements to the array |
toSource() |
Returns the source code for the 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 the 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 index of the last match |
concat()
Concatenate two or more arrays and return a new array.
Grammar:
arr.concat(a1, a2, ... , an)
Copy the code
Parameters:
arr
: target arraya1,a2,... ,an
: Elements to be merged
join()
Returns a string that concatenates the elements of two or more arrays using the specified delimiter.
To define an array
- use
new
Keyword to create onearray
Object to create an array space in memory and add elements to it. - use
new
Keyword to create onearray
Object to assign n initial values to the array. - Don’t have to
new
Direct use,[]
Declare an array, which can be given an initial value directly.
An array of operating
- Add elements
- Remove the element, pop, shift, splice.
- Through the array
- Insert the element, unshift, splice.
- Merge array
- Array to string
- Array elements in reverse order
pop
Method, which is removed from the tail, and the element is stripped from the array and returned.shift
Method, removes the element from the header, and returns.splice
Method to remove the specified element from the specified location.unshift
Method, inserted from the head.splice
Method to insert the specified number of elements from the specified location.concat
Method to concatenate multiple arrays into a single array.join
The merge () method merges the elements of an array into a string that coalesces with the specified separator.reverse
The () method changes the elements of an array in reverse order without creating a new array.sort
The () method automatically sorts the elements of an array according to certain rules (the default is the ASCII character order).
Pop () and push ()
- Pop (): changes the array by removing and returning the last element.
- Push (item): Add one or more elements to the end of an array to change the original array, returning the new array length.
The shift () and the unshift ()
- Shift (): changes the array by removing and returning the first element.
- Unshift (item): Changes the array by adding one or more elements to the array header, returning 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 an array pass the specified function test.
some()
Tests whether certain elements in the array pass the tests 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()
Executes this method on each element and returns an executed array.
Example:
let a = [1, 3, 5];
let b = a.map(function(val, index, arr){
return val + 1;
})
b; / / (2, 4, 6]
Copy the code
Extension operator
The extension operator uses (…)
Example:
console.log(... [1, 2, 3)); / / 1 2 3
console.log(1, ... [2, 3], 4); // 1, 2, 3, 4
Copy the code
// Usually shallow copy
let a1 = [1, 2];
let a2 = a1;
a2[0] = 3;
console.log(a1,a2); / / (3, 2] [3, 2]
// Extend operator deep copy
let a1 = [1, 2];
let a2 = [...a1];
// let [...a2] = a1; // The effect is the same
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()
- Used to populate an array with specified values
- Use to initialize an empty array and erase any existing elements
- The second and third arguments to fill() specify where the fill starts and ends
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()
entries()
Traversal of key-value pairskeys()
Traversal of key namesvalues()
Traversal of key values.
includes()
includes()
Indicates whether the array contains a given value- The second argument is the starting position, which defaults to 0. If it is negative, it indicates the reciprocal position, and if it is larger than the array length, it is reset to start at 0.
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); // true
Copy 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 executes a Reducer function (ascending) that you provide for 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);
/ / and is 6
var total = [ 0, 1, 2, 3 ].reduce(
( acc, cur ) => acc + cur,
0
);
Copy the code
grammar
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
The initialValue 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 an object |
String object method
String object method
attribute | instructions |
---|---|
anchor() |
Create an HTML anchor |
big() |
Display strings in large font |
blink() |
Displays a flashing string |
bold() |
Use bold to display strings |
charAt() |
Returns the character at the specified position |
charCodeAt() |
Returns the Unicode encoding of the character at the specified location |
concat() |
Connection string |
fixed() |
Displays a string in typewriter text |
fontcolor() |
Displays a string using the specified color |
fontsize() |
Displays a string with the specified size |
fromCharCode() |
Creates a string from a character encoding |
indexOf() |
Check string |
italics() |
Use italics to display strings |
lastIndexOf() |
Search strings from back to front |
link() |
Displays the string as a link |
localeCompare() |
Compare two strings in a locally specific order |
match() |
Matches of one or more regular expressions were found |
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 part in the new string |
small() |
Displays a string in small font size |
split() |
Split a string into an array of strings |
strike() |
Displays strings with strikelines |
sub() |
Displays the string as a subscript |
substr() |
Extracts the specified number of characters in a string from the starting index number |
substring() |
Retrieves the character in a string between two specified index numbers |
sup() |
Displays the string as a superscript |
toLocaleLowerCase() |
Converts a string to lowercase |
toLocaleUpperCase() |
Converts the string to uppercase |
toLowerCase() |
Converts a string to lowercase |
toUpperCase() |
Converts the 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().
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 in the string where the specified string value first appears.lastIndexOf()
.LastIndexOf (search term, start index position)
, returning the last occurrence of a specified substring value.search()
, syntax is string,Search terms
Or a stringSearch (regular expression)
.match()
, the syntax is string.match()
Retrieves a specified value within a string, or finds a match for one or more regular expressions. If there is no match, the result is returnednull
. If there’s a match, it returns an array, and the 0th element of the array holds the match text.
String interception
Substring (),slice(),substr()
substring()
, syntax is string,Substring (intercept start position, intercept end position)
.substring()
Is a common string interception method that takes two arguments, which cannot be negative, and returns a new string.slice()
, syntax is string,Slice (start position, end position)
.slice()
Can be negative, if the argument is negative, then the argument starts at the end of the string.- 1
Is the last character in a string.substr()
.Substr (intercept start position, length)
Extracts a specified number of characters from the string starting at the start of the interception. Returns a string that starts at the end of the string if the truncation starts at a negative number.
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, with the syntax string. Split (a substring used to split, which returns the maximum length of the array), returns the maximum length of the array, which is generally not set.
JS events have three stages
Flow of events:
- Event bubble flow
- Event capture stream
Event flow consists of three phases: event capture phase, target phase and event bubble phase.
- Capture, the event is received by the page element, down the level, to the specific element
- The target, the specific element itself
- Bubble, the element itself, up to the page element
- Event capture. When using event capture, the parent element fires first, and the child element fires later.
- Event bubbling. When using event bubbling, the child element fires first, and the parent element fires later.
Event bubble and event capture
- Event flow is generated when an event occurs
DOM
Flow of events:DOM
Structure is a tree structure. When an HTML element generates an event, the event is propagated between the element node and the root node in a specific order, and is received by all nodes on the path.- There are two types of event flow order: event bubbling and event capture.
Event triggering mode
Code:
addEventListener("click","doSomething","true")
Copy the code
If the third parameter is true, event capture will be used. If false, event bubble will be used.
<! 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");
// True indicates the response during the capture phase
// false indicates the response during the bubble phase
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"> </li>
< id="btn2"> Button 2</li>
<li id="btn3"> </li>
</ul>
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
webbtn.myAddFun(btn1, 'click', function(event){
Alert (' one 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 (' one click ');
break;
case "btn2":
Alert (' 2 click ');
break;
case "btn3":
Alert (' 3 click ');
break;
}
});
Copy the code
Keyboard events
Keyboard events are worlds triggered by keyboard actions.
Keyboard events:
methods | instructions |
---|---|
keydown |
Triggered when the user presses any key on the keyboard. If you hold it down, it will trigger repeatedly |
keypress |
Triggered when the user presses a character key on the keyboard. If you hold it down, it will trigger repeatedly |
keyup |
Triggered when the user releases a key on the keyboard |
Mouse drag effect
The mouse is bound to onMouseDown (), onMousemove (), and onMouseup () events.
Mouse web page, click to jump: 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 or presses the left mouse buttonEnter Key trigger |
dbclick |
The user double-clicks the mouse |
mousedown |
Triggered when the user presses any mouse button |
mouseenter |
Triggered when the mouse cursor first moves from outside the element to within the element range, without bubbling |
mouseleave |
Triggered when the cursor above the element moves outside the element’s scope, without bubbling |
mousemove |
Triggered when the cursor moves within the element |
mouseover |
The user pointer is outside an element, and then the user will first move within the bounds of another element |
mouseout |
Triggered when the user moves the cursor from one element to another |
mouseup |
Triggered when the user releases the mouse |
mousewheel |
Triggers when the wheel rolls |
Example:
function web(e) {
mouseX = e.clientX;
mouseY = e.clientY;
console.log("x:"+mouseX + "," + "y:"+mouseY)
}
<body onclick="web(event)">
Copy the code
- Mouse hover yes
onmouseover
- Mouse away is
onmouseout
Window events
Window events:
load
unload
abort
error
select
resize
scroll
Load event: when the page is fully loaded, the load event on the window will be triggered. Contains all images, JS files, CSS files and other external resources.
Example:
window.onload=function(){}
Copy the code
The function is executed when the page has 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");
// After the image is loaded, load the frame for the image
myimg.style.border = "9px solid $00ff00";
}
<img id="myimg src="" onload="imgLoad()">
Copy the code
The resize event
- Triggered when the browser window is adjusted to a new width or height
resize
Events.
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
Scrol event, the scroll event that is triggered when a document or browser window is being rolled
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"> </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 gets 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 changed the contents of the domain |
onclick |
Click on an object |
ondblclick |
Double-click on an object |
onerror |
An error occurred while loading a document or image |
onfocus |
Element gets focus |
onkeydown |
The key of a certain keyboard is pressed |
onkeypress |
Keys of a keyboard are pressed or held down |
onkeyup |
A key on a keyboard has been released |
onload |
A page or image has been loaded |
onmousedown |
A mouse button was pressed |
onmousemove |
Mouse moved |
onmouseout |
The mouse moves away from an element |
onmouseover |
The mouse is moved over an element |
onmouseup |
A mouse button has been released |
onreset |
The reset button is clicked |
onresize |
The window or frame is resized |
onselect |
Text selected |
onsubmit |
The submit button is clicked |
onunload |
User exit page |
Window events
load
The eventresize
The eventscroll
The event- “Event”
Mouse events
- Gets the mouse click location
- Mouse over and away
- The mouse to drag and drop
Keyboard event and event bubble, get
JavaScript built-in Objects
window
objectdocument
objectlocation
objectnavigator
objectscreen
objecthistory
object
JavaScript DOM operations, including getting nodes, getting, setting element attribute values, create, add nodes, delete nodes, attribute operations.
DOM
object
- When a web page loads, the browser creates a document object model for the page,
Document Object Model
, the document object model belongs toBOM
A part of theBOM
Core object indocument
Perform operations. html dom
The model is constructed as a tree of objects.
DOM
operation
The method for obtaining a node is as follows:
- The label
id
Access to:
document.getElementById(idName)
Copy the code
- The label
name
Property: Returns an array of elements
document.getElementsByName(name)
Copy the code
- Category name get: Returns an array of elements
document.getElementsByClassName(className)
Copy the code
- Tag name: Returns an array of elements
document.getElementsByTagName(tagName)
Copy the code
Gets, sets the attribute value of the element
getAttribute(attributeName)
Method, // enter the input name in parentheses, and return the attribute value of the corresponding attributesetAttribute(attributeName,attributeValue)
Method, // pass in the property name and the set value
Example:
<script>
window.onload=function(){
mytable = document.getElementById('mytable');
// Get the byte point of mytable signed tr
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 nodes
- Create a node:
Code:
// Create a node:
document.createElement("h1");
document.createTextNode(String);
document.createAttribute("class");
Copy the code
- Add a node:
Code:
element.appendChild(Node);
element.insertBefore(newNode, existingNode);
Copy the code
- 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, and set the style.
- Gets the parent node of the current element
Code:
element.parentNode
Copy the code
- Gets the child node 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
- Obtain the node type of the current node
Code:
node.nodeType
Copy the code
BOM object
BOM
Objects, called built-in objects, are the browser object model, as wellJavaScript
Is an important part of.window
-“document,location,navigator,screen,history
window
Object represents a browser windowwindow.innerHeight
Gets the internal height of the browser window,window.innerWidth
Gets the internal width of the browser window.document.documentElement.clientHeight
.document.documentElement.clientWidth
;document.body.clientHeight
.document.body.clientWidth
.- Open a new window,
window.open(url)
. - Close the current window,
window.close()
. - Resize the current window,
Window. ResizeTo (width, height)
The document object
Document attribute and method:
Properties and Methods | instructions |
---|---|
document.bgColor |
Set the page background color |
document.fgColor |
Setting the foreground Color |
document.linkColor |
Unclicked link color |
document.alinkCOlor |
Activate the color of the link |
document.vlinkColor |
The color of the link that was clicked |
document.URL |
Set url properties to open another web page in the same window |
document.cookie |
Set or readcookie |
document.write() |
Dynamically write content to the page |
document.createElement(Tag) |
Create an HTML tag object |
document.getElementById(ID) |
Get the specifiedid The object of value |
document.getElementsByName(Name) |
Get the specifiedname The object of value |
document.body |
Specifies the start and end of the document body |
document.location.href |
Full url |
document.location.reload() |
Refresh the current page |
document.location.reload(url) |
Open a new page |
Location object
The location property and method:
Properties and Methods | instructions |
---|---|
location.href |
Displays the url link of the current page |
location.port |
Displays the port of the current page link |
location.reload() |
Refreshes the current page |
The navigator object
The Navigator object contains information about the browser
attribute | instructions |
---|---|
appName |
Returns the name of the browser |
appVersion |
Returns the platform and version information for the browser |
cookieEnabled |
Returns whether enabled for the specified browsercookie Boolean value |
platform |
Return to the operating system platform on which the browser is running |
The screen object
- each
window
The object’sscreen
Attributes refer to onescrren
Object. screen
Object to hold information about the display browser screen.
Properties of a 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
history
The url object contains the url 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() |
loadinghistory The previous URL in the list |
history.forward() |
loadinghistory The next URL in the list |
history.go() |
loadinghistory A specific page in the list |
Built-in function
- String function
- The array functions
- Mathematical function
- 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 that number, rounded down |
Min (parameter 1, parameter 2) |
Return minimum |
Max (parameter 1, parameter 2) |
Return maximum value |
Pow (parameter 1, parameter 2) |
Returns the value 1 raised to the power of 2 |
random() |
Return random number |
Round (number) |
rounded |
SQRT (number) |
A square root |
Date function
set
: Used for settingDate
Object for the date and time.get
: used to obtainDate
Object for the date and time.to
: used to returnDate
Object in string format.The parse and UTC
: used for parsingDate
A string.
attribute | instructions |
---|---|
getFullYear() |
Get the full year |
getMonth() |
Get the current month |
getDate() |
Get current day |
getDay() |
Gets the day of the week |
getTime() |
Get the current time (from 1970.1.1) |
getHours() |
Gets the current number of hours |
getMinutes() |
Get 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 |
- Seconds/min: 0-59;
- When: 0-23;
- Week: 0(Sunday) – 6(Saturday)
- Dates: 1-31
- Month: 0(January) – 11(December)
- Years: number of years since 1900
Timer function
setInterval()
To call a function or evaluate an expression at a specified period.setTimeout()
Calls the function or evaluates the expression after the specified number of milliseconds.- The difference between:
setTimeout()
It only runs once,setInterval()
It executes in a loop.
function
- A function consists of four parts: the name of the function, the parameters, the body of the function, and the return value.
Code:
Function name (argument){
The body of the function
Return the return value
}
Copy the code
- There are three types of function declaration: declaration by function name, which can only be executed when the program is called; An anonymous function can be executed when called by assigning it to a variable; You can declare it in a new way. You don’t need to call it, you just execute it.
Code:
function web1 () {
document.write("1");
}
web1();
var web2 = function(){
document.write("2")
}
web2();
// This method is not used frequently
var web3 = new function(
document.write("3")
);
Copy the code
- A function may or may not return a value after execution.
- Function calls: call by value, call by address, call by function.
The closure function
- Internal functions can only be accessed from external functions
- Inner functions form closures
- You can access parameters and variables of external functions
- The outer function cannot use the parameters and variables of the inner function
- Closures can provide some security for variables of internal functions
In JS, a function defined in another function, you can access the members of the parent function, the internal function is called closed function.
A closure, short for lexical closure, is a function that references a free variable.
Closure functions have the following characteristics:
- Closures, as data paired with a function, are active during the execution of the function
- After the closure runs, the final data state during the run is maintained
- Closures, also known as lexical or function closures
- A closure is implemented as a structure that stores a function and an associated environment
- Lexical scope
Code:
function init() {
var name = "web"; // Name is a local variable created by init
Function displayName() {// displayName() is an internal 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 within the init() function body.
DisplayName () does not have its own local variable. However, because it has access to variables of external functions, displayName() can use the variable name declared in the parent function init().
The alert() statement within the displayName() function succeeds in displaying the value of the variable name, which is declared in its parent function.
This lexical scope example describes how the parser resolves variable names in the case of nested functions.
Lexical means that the lexical scope determines where a variable is available based on where it is declared in the source code. Nested functions have access to variables declared in their outer scope.
A closure is an expression (usually a function) that has many variables and the environment to which they are bound, so that the variables are also part of the expression.
All functions in JavaScript are a closure. In general, though, nested functions produce closures that are more powerful, and are what we call “closures” most of the time.
What closures do
After A executes and returns, the closure allows Javascript’s garbage collection mechanism, GC, not to reclaim resources from A, because the execution of A’s internal function B depends on variables in A.
- Function excution Context
- Live Object (Call Object)
- Scope (scope)
- 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:
- Use the let added in ES6.
- 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 variables can cause variable promotion problems:
for(var i = 0 ; i<10; i++)
{
console.log(i)
};
console.log(i);
// Variable promotion returns 10
Copy the code
object
- There are two ways to declare an object: by
new 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 a regular expression
Using a regular expression literal:
let reg = /ab+c/;
let reg = /^[a-zA-z]/gi;
Copy the code
- Can’t remember, can’t remember, can’t remember.
- A regular expression is a literal pattern composed of ordinary characters and special characters.
- Regular expressions contain match characters, locators, qualifiers, escape characters, and so on.
- There are two methods in regular expressions: string methods and regular object methods.
String method
attribute | instructions |
---|---|
search() |
Retrieves the value that matches the regular expression |
match() |
Matches of one or more regular expressions were found |
replace() |
Replace a string with a regular expression |
split() |
Split a string into an array of strings |
Regular object method
RegExp object method
attribute | instructions |
---|---|
test() |
Detects whether a string matches a pattern |
exec() |
This method is used to retrieve the match of a regular expression in a string. This function returns an array |
[a-z]
Matches any of the lowercase letters from a to Z
Copy the code
[A-Z]
Matches any of the uppercase letters from A to Z
Copy the code
[0-9]
Matches any character of the numbers 0 through 9, equal to \d
Copy the code
[0-9a-z]
Matches any character from the digits 0 through 9 or lowercase letters A through Z.
Copy the code
[0-9a-zA-Z]
Matches any character in the numbers 0 through 9 or lowercase A through Z or uppercase A through Z
Copy the code
[abcd]
Matches any character in the character ABcd
Copy the code
[^a-z]
Matches any character except lowercase letters A through Z
Copy the code
[^ 0-9]
Matches any character except the digits 0 through 9
Copy the code
[^abcd]
Matches any character except abcd
Copy the code
Metacharacters are characters that have special meanings:
.
Finds single characters, except newlines and line terminators.
Copy the code
\w
Find word characters.
Copy the code
\W
Find non-word characters.
Copy the code
\d
Look for numbers.
Copy the code
\D
Find non-numeric characters.
Copy the code
\s
Find whitespace characters.
\S
Find non-whitespace characters.
Copy the code
\ 0
Find the NUL character.
\n
Look for newline characters.
\f
Find the page feed character.
\r
Look for carriage returns.
\t
Look for tabs.
\v
Find the vertical TAB.
Copy the code
\xxx
Finds characters specified in the octal number XXX.
\xdd
Finds characters specified as a hexadecimal number dd.
\uxxxx
Finds a Unicode character specified as a 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. |
n? |
A string of zero or one n. |
n{X} |
A string of X sequences of n. |
n{X,Y} |
A string consisting of X to Y sequences of n. |
n{X,} |
A string of at least X sequences of n. |
n$ |
Matches any string ending in n. |
^n |
Matches any string that starts with n. |
? =n |
Matches any string followed by the specified string n. |
? ! n |
Matches any string that is not immediately followed by the specified string n. |
The locator
Locators can fix a regular expression at the beginning or end of a line, or they can create regular expressions that occur only within words or at the beginning or end of words.
Copy the code
^
Matches the starting position of the input string
Copy the code
$
Matches the end of the input string
Copy the code
\b
Matches a word boundary
Copy the code
\B
Matches non-word boundaries
Copy the code
/ ^] [\ d {4} [d \] {1, 2} -] [\ d {1, 2} ${1, 2} $] /
The date of character
Copy the code
Escape character
Escape using an escape character (backslash \)
Copy the code
New RegExp(STR [, attr]) takes two arguments. STR is a string that specifies the matching rules of the regular expression. Attr is optional and indicates the matching pattern.
Expressions: g, I,m
G stands for global mode
Applies to all strings, rather than stopping at the first match
I indicates case insensitive mode
M stands for multi-line mode
Continue to look in the next line for an item that matches the pattern
Copy the code
The modifier | describe |
---|---|
i |
Performs case-insensitive matching. |
g |
Perform a global match. |
m |
Perform multi-line matching. |
The arguments object
The actual arguments to the function are stored in an array-like object called Arguments. The arguments are indexed:
var a = arguments[i]
Copy the code
- use
arguments.length
To get the number of actual parameters passed in arguments
Object to get each parameter
The text box lost the focus event and gained the focus event
OnBlur: This event is generated when 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 three best time periods for memory
- 2 hours before bedtime
- An hour after getting up
- 8 to 10 o ‘clock in the morning
β€οΈ Thank you all
1. If this article is helpful to you, give it a like. Your likes are my motivation.
2. Add wechat [Xiaoda0423], pull you into the technical exchange group to learn together.