5 Days Speedrun JavaScript

5 Days Speedrun JavaScript

First, what is JavaScript and its function?

JavaScript ("JS" for short) is currently the most popular and widely used client-side scripting language, which is used to add some dynamic effects and interactive functions to web pages.
JavaScript is used to update the content of the webpage in real time, such as obtaining data from the server and updating it to the webpage, modifying the style of some tags or the content in it, etc., which can make the webpage more vivid.

Second, the composition and characteristics of JavaScript

Core (ECMAScript): Provides the syntax and basic objects of the language;
insert image description here

Document Object Model (DOM): Provides methods and interfaces for processing web content;
Browser Object Model (BOM): Provides methods and interfaces for interacting with browsers.
features

2. Introduction to JavaScript

The use of JavaScript (divided into two types of tags)
1. Embedded Embedded
in the hand of HTML

<script>
    alert("Hello,World!");  #alert("这里是要想输出的语句")
</script>

2. The external chain
is also embedded in the hand

<script src="main.js"></script>  #在同一个文件夹下创建main.js文件,如:alert("Hello,World!");


It should be noted here that the script tags should appear in pairs, that is, do not write it. <script src="main.js"/>这是错误的方式.
In the new version of the programming software, it is not necessary to define the type type in the script
insert image description here

Three, JavaScript comments

Single-line comment: // comment content
Multi-line comment: /* comment content */

Fourth, the use of the browser console

Right-click to inspect elements in the browser (press f12)
Elements: HTML and CSS of the web page.
Console: The console can write Javascript code and output {console.Log(score) to print variables on the console of the browser! Equivalent to sout}.
Sources: The current source code directory, which can be debugged (code break point).
Netbook: Network request data.
Application: The database in the web stores some simple data in the browser

insert image description here

Five, basic grammar

JavaScript is strictly case sensitive

1. Define variables

assignment (single-line assignment)

var num = 1; #变量类型    变量名 = 变量值

copy multiple lines

var num = 1;                // 定义一个变量 num 并将其赋值为 1
var a = 2, b = 3, c = 4;    // 同时定义 a、b、c 三个变量并分别赋值为 2、3、4
// var a = 2,               // 为了让代码看起来更工整,上一行代码也可以写成这样
//     b = 3,
//     c = 4;      

2. Condition control

insert image description here

3. Data type (object type)

Basic data type (value type):
string (String), number (Number), Boolean (Boolean), empty (Null), undefined (Undefined), Symbol

Reference data type:
object (Object), array (Array), function (Function)

Note:
Symbol is a new data type introduced in ECMAScript6
refers to:
a unique value

primitive data types (value types)

String (String)

'abc' "abc"
boolean value
true, false
1, normal string we use single quotes, or double quotes wrap
2, pay attention to the escape
insert image description here
character string definition

      方式一(推荐):  var str = ‘亲’;    //基本类型 
      定义了一个字符串变量str,内容为'亲'
 
      方式二: var str = new String(“hello”);       //引用类型
      定义一个字符串变量str,内容为hello,
      注意: 此刻str为引用类型(object对象)
      用new产生的变量都是引用类型的变量,也叫对象
 
      方式三: var str = String(‘hello’);
      基本类型: string, number, boolean, undefined,null等
      引用类型/对象: Array , Date, Object, String, Function等

#3.new String()和String()的区别
当String()和元素符new一起使用, 那么String()是作为构造函数使用的,它返回的是一个新创建的String对象. 当不用new运算符调用String()时,它只是转换成原始的字符串,并返回转换后的值.

String properties and methods
insert image description here

number (js does not distinguish between integers and decimals)

insert image description here

Number定义数值注意事项:
   1.Number定义的数值有数据范围限制
      Number只能表示“负2的53次方减一” 到 “2的53次方减1”之间的数值
   2.当出现极大数值时,可以使用一些特殊值表示
      如:
	  Infinity:
	     表示正无穷大的数值
		  一般指大于 1.7976931348623157e+308 的数;
      -Infinity:
	     表示负无穷大的数值
		  一般指小于 5e-324 的数;
   3.NaN(非数值Not a Number) 表示无效的数字    

Boolean type

The Boolean type has only two values:
1.true (true)
2.false (false)
The Boolean type is often used for value judgment`

var a = true;   // 定义一个布尔值 true
var b = false;  // 定义一个布尔值 false
var c = 2 > 1;  // 表达式 2 > 1 成立,其结果为“真(true)”,所以 c 的值为布尔类型的 true
var d = 2 < 1;  // 表达式 2 < 1 不成立,其结果为“假(false)”,所以 c 的值为布尔类型的 false

bold style

Null type

Null is a special data type with only one value,
which means empty value, there is no value, and it is often used to define empty object pointer

Note:
typeof(null) can see that the result is Object

Undefined type

Undefined is a special data type with only one value.
When we declare a variable but do not assign a value to the variable,
the default value of the variable is Undefined.

var a;
console.log(a);  // 输出 undefined

typeof(a) 会返回undefined 

var m;
console.log(typeof m);  // 输出 undefined
console.log(typeof t);     // 输出 undefined

Symbol type

Symbol is a new data type introduced in ECMAScript6.
It refers to the unique value of
Symbol type. The value of Symbol type needs to be generated using the Symbol() function.

var str = "888";
var sym1 = Symbol(str);
var sym2 = Symbol(str);
console.log(sym1);          // 输出 Symbol(123)
console.log(sym2);          // 输出 Symbol(123)
console.log(sym1 == sym2);  
// 输出 false
// 虽然 sym1 与 sym2 看起来是相同
// 但实际上它们并不一样
// 根据 Symbol 类型的特点
// sym1 和 sym2 都是独一无二的

How to determine the data type

To detect data types in JavaScript, we thought of an operator at this time,
that is the typeof operator

Introduction to the typeof operator:
the function of the typeof operator is used to return the data type of the variable
typeof operator syntax:
typeof x; //return the data type of the variable x
typeof(x); //return the data type of the variable x

JS reference data type

Object type

The Object type in JavaScript
is an unordered set of keys and values. Curly
braces { } are required to define the object type.

{name1: value1, name2: value2, name3: value3, ..., nameN: valueN}

name1、name2、name3、...、nameN:
   为对象中的键
value1、value2、value3、...、valueN:
   为对应的值

Object type definition example

ar person = {
    name: 'maomao',
    age: 18,
    tags: ['js', 'python', 'java'],
    city: 'ShenZhen',
    hasCar: true,
    zipcode: null
};
console.log(person.name);       // 输出 maomao
console.log(person.age);        // 输出 18

Array type

Array (Array):
refers to a collection of data arranged in order.
Each value in the array is called an element
, and the array can contain any type of data

To define an array in JavaScript, you need to use square brackets [ ]
to separate each element in the array with a comma

//定义方式1
var arr =[88, 2, 3, 'python', true, null]

//定义方式2
var arr = new Array(88, 2, 3, 4);
console.log(arr);       // 输出 [88, 2, 3, 4]

//访问数组的方式
 var arr = [88, 2, 3.14, 'Python', null, true];
console.log(arr[0]);  // 输出索引为 0 的元素,即 8
console.log(arr[5]);  // 输出索引为 5 的元素,即 true
console.log(arr[6]);  // 索引超出了范围,返回 undefined

Function type

Function (Function)
is a block of code with a specific function.
The function does not run automatically.
It can only be run by calling the function name.

function sayHello(name){
    return "Hello, " + name;
}
var res = sayHello("Maomao");
console.log(res);  // 输出 Hello, Maomao

Liezi

var fun = function(){
    console.log("https://www.linux28.com/js/");
}

function createGreeting(name){
    return "Hello, " + name;
}

function displayGreeting(greetingFunction, userName){
    return greetingFunction(userName);
}

var result = displayGreeting(createGreeting, "Maomao");
console.log(result);  // 输出 Hello, Maomao

Six, JavaScript operators

Introduction to operators Operators
are symbols operated by the JavaScript engine
such as:
plus sign (+): addition operation minus
sign (-): subtraction operation

arithmetic operator

Arithmetic operators:
used to perform common mathematical operations
such as:
addition, subtraction, multiplication, division, etc.
*

var x = 100,
    y = 40;
console.log("x + y =", x + y);  // 输出:x + y = 140
console.log("x - y =", x - y);  // 输出:x - y = 60
console.log("x * y =", x * y);  // 输出:x * y = 4000
console.log("x / y =", x / y);  // 输出:x / y = 2.5
console.log("x % y =", x % y);  // 输出:x % y = 2

assignment operator

insert image description here

var x = 20;
x += 30;
console.log(x);  // 输出:50
var x = 18,
    y = 9;
x -= y;
console.log(x);  // 输出:9
x = 6;
x *= 36;
console.log(x);  // 216
x = 60;
x /= 20;
console.log(x);  // 输出:3
x = 100;
x %= 15;
console.log(x);  // 输出:10

string operators

In JavaScript syntax:
+ and += operators: In addition to mathematical operations,
they can also be used to concatenate strings
Among them:
The function of the + operator: splice the strings on the left and right sides of the operator together
+= operator The function of: concatenate the strings
and then assign the result to the variable on the left side of the operator

var x = "linux ";
var y = "YHW";
var z = x + y;
console.log(z);  // 输出:linux YHW
x += y;
console.log(x);  // 输出:linux YHW

Increment and decrement operators

The self-increment and self-decrement operators are used to
perform self-increment (+1) and self-decrement (-1) operations on the value of a variable
insert image description here

var x;
x = 10;
console.log(++x);  // 输出:11
console.log(x);    // 输出:11
x = 10;
console.log(x++);  // 输出:10
console.log(x);    // 输出:11
x = 10;
console.log(--x);  // 输出:9
console.log(x);    // 输出:9
x = 10;
console.log(x--);  // 输出:10
console.log(x);    // 输出:9

comparison operator

The expression used to compare the left and right sides of the operator.
The result of the comparison operator is a Boolean value.
There are only two results: either true or false

insert image description here
insert image description here

var x = 88;
var y = 99;
var z = "88";
console.log(x == z);  // 输出: true
console.log(x === z); // 输出: false
console.log(x != y);  // 输出: true
console.log(x !== z); // 输出: true
console.log(x < y);   // 输出: true
console.log(x > y);   // 输出: false
console.log(x <= y);  // 输出: true
console.log(x >= y);  // 输出: false

Logical Operators:

Often used to combine multiple expressions
The result of a logical operator is a Boolean value, returning true or false

with, or, not
insert image description here

ternary operator

Consists of a question mark and a colon

The syntax format is as follows:
conditional expression? expression 1 : expression 2 ;
when the result of the "conditional expression" is true (true)
, execute the code in "expression 1", otherwise execute the code in "expression 2" code.

var x = 22,
    y = 88;
x > y ? console.log("x 大于 y") : console.log("x 小于 y");  // 输出:x 小于 y

bitwise operator

It is JavaScript that performs bit manipulation on binary
insert image description here

var a = 5 & 1,
    b = 5 | 1,
    c = 5 ^ 1,
    d = ~ 5,
    e = 5 << 1,
    f = 5 >> 1,
    g = 5 >>> 1;
console.log(a);  // 输出:1
console.log(b);  // 输出:5
console.log(c);  // 输出:4
console.log(d);  // 输出:-6
console.log(e);  // 输出:10
console.log(f);  // 输出:2
console.log(g);  // 输出:2

Seven, the way JavaScript outputs information

Method 1:
alert() function to pop up a prompt box

Method 2:
confirm() function to pop up a dialog box

Method 3:
The document.write() method writes the content into the HTML document

Method 4:
innerHTML writes content into HTML tags

Method 5:
console.log() outputs content in the browser console

alert function example

在这里插入代码片 alert(提示框中输出的内容);
 alert函数的另一种写法:
    window.alert(提示框中输出的内容) 

confirm() function

The confirm() function is similar to the alert() function. They are all the information prompted by the confirm() function
under the window object : there will be an OK and Cancel button . Click "OK" and it will return true. Click "Cancel" and it will return false.



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var res = window.confirm("这里是要显示的内容");
        if(res == true){
            alert("你点击了“确定”按钮");
        }else{
            alert("你点击了“取消”按钮");
        }
    </script>
</body>
</html>

console.log()

The function of the console.log() function:
output information to the browser's console

console.log() syntax:
console.log(message);
parameter description:
message: the content to be output

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var arr = ["Chrome","Firefox","Edge","Safari","Opera"];
        console.log(arr);
    </script>
</body>
</html>

document.write()

The function of the document.write() method:
write html information to the html document
Note:
write html information, it will be rendered and run by the browser

Syntax of the document.write() method:
document.write(exp1, exp2, exp3, ...);
Parameter description:
exp1, exp2, exp3:
the content written to the document
Note:
document.write() can receive multiple Parameters, separated by commas

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        document.write("<p>现在的时间是:</p>");
        document.write(Date());
    </script>
</body>
</html>

innerHTML

innerHTML is an attribute:
with this attribute, the content in the specified html tag can be set

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <div id="demo">JavaScript 输出</div>
    <script type="text/javascript">
        var demo = document.getElementById("demo");
        console.log(demo.innerHTML);
        demo.innerHTML = "<h2>innerHTML</h2>"
    </script>
</body>
</html>

Eight, JavaScript conditional judgment

(if else) statement

Grammatical style of conditional judgment statement
if statement
if else statement
if ,else if, else statement

if statement

if(条件表达式){
    // 要执行的代码;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var age = 22;
        if(age >= 22){      //当age >= 22结果为 true,则运行{ }中的代码
            alert("你已经22岁了!");
        }
    </script>
</body>
</html>

if else statement

if else 语句:
   是 if 语句的升级版
   它可以设置当前布尔表达式满足条件时,运行相应的代码
    同时还指定了不满足条件时,运行相应的代码

if else语法样式:

if(条件表达式){
    // 当表达式成立时要执行的代码
}else{
    // 当表达式不成立时要执行的代码
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
         var age = 22;
        if(age >= 22){      //当age >= 22结果为 true,则运行{ }中的代码
            alert("你已经22岁!");
        }else{
		    alert("你不是22岁!");
		}
    </script>
</body>
</html>

if else statement

if else 语句:
   是 if 语句的升级版
   它可以设置当前布尔表达式满足条件时,运行相应的代码
    同时还指定了不满足条件时,运行相应的代码

if else语法样式:

if(条件表达式){
    // 当表达式成立时要执行的代码
}else{
    // 当表达式不成立时要执行的代码
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
         var age = 22;
        if(age >= 22){      //当age >= 22结果为 true,则运行{ }中的代码
            alert("你已经22岁!");
        }else{
		    alert("你不是22岁!");
		}
    </script>
</body>
</html>

if ,else if, else statement

if ,else if, else 语句:
    在条件判断语句中定义多个分支
	只要一个分支符合条件,则运行下面的代码

if (条件表达式 1) {
    // 条件表达式 1 为真时执行的代码
} else if (条件表达式 2) {
    // 条件表达式 2 为真时执行的代码
}
...
  else if (条件表达式N) {
    // 条件表达式 N 为真时执行的代码
} else {
    // 所有条件表达式都为假时要执行的代码
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var now = new Date();           // 获取当前的完整日期
        var dayOfWeek = now.getDay();   // 获取一个 0-6 之间的数字,用来表示当前是星期几,0 表示星期日、1 表示星期一、以此类推
        if(dayOfWeek == 0) {            // 判断当前是星期几
            alert("星期日")
        } else if(dayOfWeek == 1) {
            alert("星期一")
        } else if(dayOfWeek == 2) {
            alert("星期二")
        } else if(dayOfWeek == 3) {
            alert("星期三")
        } else if(dayOfWeek == 4) {
            alert("星期四")
        } else if(dayOfWeek == 5) {
            alert("星期五")
        } else {
            alert("星期六")
        }
    </script>
</body>
</html>

JS switch case statement


The switch statement compares with the value in the case clause in sequence according to the value of the expression
. When the two are equal, run the subsequent statement segment.
When encountering the break keyword, jump out of the entire switch statement
. If they are not equal, continue to match the next case

The switch statement contains an optional default keyword.
When no equal condition is found in the previous case, the statement following the default is executed.

switch case语法结构:
    switch (表达式){
    case value1:
        statements1  //当表达式的结果等于 value1 时,则执行该代码
        break;
    case value2:
        statements2  //当表达式的结果等于 value2 时,则执行该代码
        break;
    ......
    case valueN:
        statementsN  //当表达式的结果等于 valueN 时,则执行该代码
        break;
    default :
        statements  //当没有与表达式相同的值,则执行该代码
   }

switch case statement keywords

break keyword
The function of the break keyword:
used to jump out of the switch statement, of course break can also jump out of for, for in, while, do while and other operating statements

The switch keyword runs line by line.
When the switch encounters a case statement that matches successfully, we don’t want the program to continue running downwards at this time, so we need to add the break keyword at the end of the case
to achieve the effect of the switch keyword running.

switch (id) {
    case 1 :
        console.log("id=====1");
        break;  //停止执行,跳出switch
    case 2 :
        console.log("id=====2");
        break;  //停止执行,跳出switch
    case 3 :
        console.log("id=====3");
        break;  //停止执行,跳出switch
    default :  //上述条件都不满足时,默认执行的代码
        console.log("id不是1,2,3 !");
}

case clause

case statement:
followed by the specific conditional code
case statement:
it can also be omitted

var id = 1;
switch (id) {
    case 1 :
    case 2 :
        console.log("id ===2");
        break;
    case 3 :
        console.log("id ===3");
        break;
    default : 
        console.log("id不等于2,也不等于3");

default statement

default is the switch clause,
located anywhere in the switch,
it will not affect the normal execution of other case clauses

Note:
There is a case statement after default, and
the break keyword must be added after default
, otherwise the case after default will run

var id = 1;
switch (id) {
    default : 
        console.log("default");
        break;
    case 1 : 
        console.log("===1===");
        break;
    case 2 :
        console.log("===2===");
        break;
    case 3 :
        console.log("===3===");
        break;
}


//例2

var id = 3;
switch (id) {
    default : 
        console.log("default");
    case 1 :
        console.log("===1===");
    case 2 :
        console.log("===2===");
}

Nine, JS loop statement

while loop statement

When the while loop statement meets the conditions, the code block behind the while condition can continue to run
javascript's while loop
while (conditional expression) { // code to be executed }


The while loop will first evaluate the conditional expression before each loop.
When the result of the conditional expression is true,
the code in { } will be run.
When the result of the conditional expression is false
, the while loop will be exited, and
the code after the while loop will be run.

Note:
If the conditional expression is written unreasonably,
it will cause an infinite loop

Output a number between 1-10

var i = 1;
while( i <= 10) {
    document.write(i+", ");
    i++;
}

Use while loop to calculate the sum of all integers between 1 and 100

var i=1;
var sum=0;
while (i <= 100){
    sum += i;
    i++;
}
document.write("1 + 2 + 3 + ... + 98 + 99 + 100 = " + sum)

do while loop statement

The function of the do while loop statement:
run the following statement first
and then judge whether the condition is true
or false If the condition is true, continue to run the code behind do while
If the condition is false, exit the while loop, and the program continues to run downward

do while syntax:

do { //Code to run after the condition is met } while (conditional expression);

var i = 1;
do{
    document.write(i + " ");
    i++;
}while (i > 8);

do while find the sum of all values ​​from 1 to 100

var i=1;
var sum=0;
do {
    sum += i;
    i++;
} while (i <= 100);
document.write("1 + 2 + 3 + ... + 98 + 99 + 100 = " + sum)

for loop statement

for loop statement:
loop according to the incoming conditions

The syntax of the for loop:
for(initialization; condition; increment) { // code to be executed } #initialization: for an expression or variable declaration, we usually call this step " initializing the counter variable", in the loop process only will execute once;




condition:
It is a conditional expression, which has the same function as the conditional expression in the while loop. It
is usually used to compare with the value of the counter to determine whether to loop.
The number of loops can be set through this expression;

increment:
is an expression used to update (increment or decrement) the value of the counter after each loop

for (var i = 1; i <= 10; i++) {
    document.write(i + " ");
}

Nested for loop - print 9*9 multiplication formula

for (var i = 1; i <= 9; i++) {
    for (var j = 1; j <= i; j++) {
        document.write(j + " x " + i + " = " + (i * j) + " ");
    }
    document.write("<br>");
}

for in loop statement

The for in loop in Javascript:
is a special type of loop
that is a variant of the normal for loop

The function of for in:
traversing the object
Use it to cycle out the properties in the object in turn

The syntax of for in:
for (variable in object) { //code to be run }

// 定义一个对象
var person = {"name": "maomao", "surname": "adeal", "age": 12};
// 遍历对象中所有属性
for(var prop in person) {
    document.write("<p>" + prop + " = " + person[prop] + "</p>");
}

----运行以上代码,将输出以下信息-----
name = maomao
surname = adeal
age = 12

for of loop statement

for of loop:
It is a new loop mode added in ECMAScript6,
which is similar to for in and is a variant of ordinary for loop

The application scenario of the for of loop:
traversing arrays or other traversable objects
such as:
strings, objects, etc.

The syntax of the for of loop is as follows:

for (variable of iterable) { // code to be executed } #variable: the variable of the single row data cache in each cycle iterable: the content to be traversed



// 定义一个数组
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
// 使用 for of 循环遍历数组中的每个元素
for (var value of arr) {
    document.write(value + ", ");
}
document.write("<br>");


// 定义一个字符串
var str = "Hello linux28.com 我最爱的教程站!";
// 使用 for of 循环遍历字符串中的每个字符
for (var value of str) {
    document.write(value + ", ");
}
document.write("<br>");


// 定义一个对象
var obj = {"name": "maomao", "surname": "adeal", "age":18};
// 使用 for of 循环遍历对象中的所有属性
for(var value in obj) {
    document.write(value + ", ");
}

Ten, break and continue jump out of the loop

Three situations for jumping out
1. When the for loop runs halfway, jump out
2. For loop - a single code block - run halfway, go directly to the next loop
3. While loop terminates, etc.

How to jump out
of the loop in javascript can be achieved by using the break and continue keywords

break:
directly terminate the current loop

continue:
Jump out of the loop and enter the next item in the loop

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8"> 
  <title>linux28.com 跳出循环示例</title>
 </head>
 <body>
   <script>
   for (var i = 0; i < 10; i++) {
    if(i == 5) {
        break;
    }
      document.write("i = " + i + "&nbsp; &nbsp;");
    }

     document.write("<hr>");
     
	for (var i = 0; i < 10; i++) {
    if(i % 2 == 0) {
        continue;
    }
      document.write(i + "&nbsp;");
   }

   </script>
 </body>
</html>

Eleven, function

Functions in javascript are divided into built-in functions and self-built functions (function:
is a set of task codes, usually the function will be run multiple times)

function

Function syntax:
function functionName(parameter_list) { // code in the function }

function sayHello(name){
    document.write("Hello " + name);
}

Call functions

Just enter the function name and function parameters

function sayHello() {
  console.log("Hello!");
}

sayHello(); // 调用函数

Another way to call a function is to trigger it through an event, such as calling a function when a button is clicked. This calling method needs to bind the function name to the corresponding event

<button onclick="sayHello()">Click me</button>

Default values ​​for parameters in functions

Set a default value
so that when we call this function,
if no parameter information is entered, the default value will be used

function greet(name = "World") {
  console.log(`Hello, ${name}!`);
}

greet(); // 输出 "Hello, World!"
greet("Alice"); // 输出 "Hello, Alice!"

Setting default values ​​for multiple parameters

function foo(a, b = 0, c = 1) {
  console.log(a, b, c);
}

foo(10); // 输出 "10 0 1"
foo(10, 20); // 输出 "10 20 1"
foo(10, 20, 30); // 输出 "10 20 30"

function expression

Basic syntax:

const functionName = function(parameters) {
  // function body
};
functionName 是变量名,可以随意命名,用于引用该函数;parameters 是函数的参数列表;function body 是函数体

In the code below, we define an anonymous function called greet using a function expression and assign it to the greet variable. Then we call the greet function, passing in the parameter "Alice", and outputting Hello, Alice!.

const greet = function(name) {
  console.log(`Hello, ${name}!`);
};

greet("Alice"); // 输出 "Hello, Alice!"

// 两种不同的写法
// 函数声明
function getSum(num1, num2) {
    var total = num1 + num2;
    return total;
}
// 函数表达式
var getSum = function(num1, num2) {
    var total = num1 + num2;
    return total;
};

Twelve, JS event function

JS event (event):

用于用户同网页进行交互操作
  如:
    单机某个链接或按钮
    在文本框中输入文本
    按下键盘上的某个按键、移动鼠标等
    当事件发生时

Notes on JS events:
JS events start with on,
such as: onclick, onload, etc.

鼠标、键盘事件	
onclick	点击鼠标时触发此事件
ondblclick	双击鼠标时触发此事件
onmousedown	按下鼠标时触发此事件
onmouseup	鼠标按下后又松开时触发此事件
onmouseover	当鼠标移动到某个元素上方时触发此事件
onmousemove	移动鼠标时触发此事件
onmouseout	当鼠标离开某个元素范围时触发此事件
onkeypress	当按下并松开键盘上的某个键时触发此事件
onkeydown	当按下键盘上的某个按键时触发此事件
onkeyup	当放开键盘上的某个按键时触发此事件
窗口事件	
onabort	图片在下载过程中被用户中断时触发此事件
onbeforeunload	当前页面的内容将要被改变时触发此事件
onerror	出现错误时触发此事件
onload	页面内容加载完成时触发此事件
onmove	当移动浏览器的窗口时触发此事件
onresize	当改变浏览器的窗口大小时触发此事件
onscroll	当滚动浏览器的滚动条时触发此事件
onstop	当按下浏览器的停止按钮或者正在下载的文件被中断时触发此事件
oncontextmenu	当弹出右键上下文菜单时触发此事件
onunload	改变当前页面时触发此事件
表单事件	
onblur	当前元素失去焦点时触发此事件
onchange	当前元素失去焦点并且元素的内容发生改变时触发此事件
onfocus	当某个元素获得焦点时触发此事件
onreset	当点击表单中的重置按钮时触发此事件
onsubmit	当提交表单时触发此事件

event binding

Refers to the event is bound to the html element, and then triggered by the event

onclick attribute example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <button type="button" onclick="myBtn()">按钮</button>
    <script type="text/javascript">
        function myBtn(){
            alert("Hello World!");
        }
    </script>
</body>
</html>

The second way of event binding

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <button type="button" id="myBtn">按钮</button>
    <script>
        function sayHello() {
            alert('Hello World!');
        }
        document.getElementById("myBtn").onclick = sayHello;
    </script>
</body>
</html>

onmouseover event

Event fired when the user moves the mouse pointer over an element

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <button type="button" 
	   onmouseover="alert('您的鼠标已经移动到了该按钮上');">
	    请将鼠标移动至此处</button><br>
    <a href="#" onmouseover="myEvent()">请将鼠标移动至此处</a>
    <script>
        function myEvent() {
            alert('您的鼠标已经移动到了该链接上');
        }
    </script>
</body>
</html>

onmouseout event

The onmouseout event is just the opposite of the onmouseover event, and the onmouseout event is triggered when the mouse leaves the element

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <div style="width: 350px; height: 200px; border:1px solid black" id="myBox"></div>
    <script>
        function myEvent() {
            alert('您的鼠标已经离开指定元素');
        }
        document.getElementById("myBox").onmouseout = myEvent;
    </script>
</body>
</html>

onkeydown event

The onkeydown event refers to the event that is triggered when the user presses a key on the keyboard

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <input type="text" onkeydown="myEvent()">
    <script>
        function myEvent() {
            alert("您按下了键盘上的某个按钮");
        }
    </script>
</body>
</html>

onkeyup event

Event fired when the user presses and releases a key on the keyboard (i.e. presses and releases a key)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <input type="text" onkeyup="myEvent()">
    <script>
        function myEvent() {
            alert("您按下了键盘上的某个按钮,并将其释放了");
        }
    </script>
</body>
</html>

Thirteen, JS scope

Scope refers to:
the visible scope of variables, we call this scope "scope"

JS scope is divided into the following two types:
global scope and local scope

global scope

Global scope means:
Variables can be accessed anywhere in the current script. Variables with global scope are also called "global variables". Generally, variables with the following characteristics have global scope.
Have a global scope:
1. The outermost function and variables defined outside the outermost function have a global scope;
2. All variables that do not define direct assignment have a global scope;
3. All properties of the window object have a global scope Scope
such as:
window.name, window.location, window.top, etc.

var str = "Hello YHW!";
function myTest(){
    document.write(str);    // 输出:Hello YHW!
}
myTest();
document.write(str);        // 输出:Hello YHW!
全局作用域变量都会绑定到window对象
	作为window对象的一个属性存在
var str = "JavaScript";
document.write(str);                    // 输出:JavaScript
document.write(window.str);             // 输出:JavaScript
document.write(str === window.str);     // 输出:true

local scope

Variables declared inside a function have local scope
Variables with local scope are also called "local variables"
Local variables can only be used within their scope (inside a function)

Note:
The local variables defined in the function will only be generated when the function is called, and
will be destroyed immediately after the function is executed

function myTest(){
    var str = "Hello YHW!";
    document.write(str);    // 输出:Hello YHW!
}
myTest();
document.write(str);        // 报错:str is not defined

Fourteen, JS objects and properties

The difference between objects and types

In JavaScript, primitive types (primitive values) and objects are two different concepts. The basic types in JavaScript include Number, String, Boolean, null, undefined, and Symbol (newly added in ES6). They are immutable, simple value types, and are stored in stack memory; while objects are reference types that can be dynamically Add or delete attributes, stored in heap memory.

However, in order to facilitate the processing of basic types of data, JavaScript provides corresponding wrapper objects, namely Number, String, Boolean, null and undefined. These wrapper objects provide many useful methods and properties for us to use, such as Number.toFixed(), String.length, and so on. When we call a method or property on a basic type, JavaScript will temporarily convert the basic type into a corresponding wrapper object, and then call the corresponding method or property. This process is called "autoboxing".

How to create objects in JS

Use curly braces { } to create an object. { }
contains:
define the properties in the object.
The property is a combination of key: value pairs.
The key (property name) is always a string type
value (property value) and can be any Types
such as:
strings, arrays, functions or other objects, etc.
Different attributes are separated by commas
such as name (name), age (age), gender (sex)

var person = {
    name: "maomao",
    age: 16,
    gender: "FeMale",
    displayName: function() {
        document.write(this.name);
    }
};

//相关说明
//displayName是对象中的属性,
//function() {
        document.write(this.name);
    }
是属性值

Javascript access attribute value

There are two ways to access the property value:
using object name comma property name
or
object name["property name"]

Note:
When the attribute name is irregular, you need to use quotation marks to enclose the attribute name
or use a variable name as the attribute name

document.write("姓名:" + person.name + "<br>");   // 输出:姓名:maomao
document.write("年龄:" + person["age"]);          // 输出:年龄:16

var k ="name";
document.write("姓名:" + person[k] + "<br>");   // 输出:姓名:maomao

delete object property

Use the delete keyword to delete properties in js objects

delete object name.property name
delete object name["property name"]
delete object name[property name]

Note:
1. Changing the attribute value to undefined or null will only modify the attribute value
and will not delete the object attribute
2. Deleting the object attribute can only be done by the delete keyword

delete person.name
delete person.age
delete person.gender

call a method on an object

Use object name. property name ()
or
object name "property name"
to call the method in the property

person.displayName();       // 输出:maomao
person["displayName"]();    // 输出:maomao

Number (number) object

JavaScript does not distinguish between integers and floating-point numbers.
All numbers use the 64-bit floating-point format of the IEEE754 standard (binary floating-point arithmetic standard) to represent digital
Number objects .

The syntax for creating a Number object is as follows:
var myTest = new Number(value);
var myTest = Number(value);

value: non-numeric value, if it cannot be converted at this time, it will return NaN

var a = new Number("8888");
var b = Number("9999");
var c = 678;
var d = new Number("abc");
document.write(typeof a + "<br>");      // 输出:object
document.write(typeof b + "<br>");      // 输出:number
document.write(typeof c + "<br>");      // 输出:number
document.write(d + "<br>");             // 输出:NaN

Maximum numeric value in JavaScript:

 Number.MAX_VALUE

Maximum numeric value in JavaScript:

  Number.MIN_VALUE
var x = 898;    // 整数
var y = 8.75;   // 浮点数
var z = 0xff;   // 十六进制数:255

//当遇到比较大的数字时
//我们可以使用指数法表示

//如:
var x = 1.67e4;     // 等于 16700
var y = 4.36e+6;    // 等于 4360000
var z = 4.36e-6;    // 等于 0.00000436

注意事项:
  JavaScript 中能够表示的最大的整数是 2⁵³ - 1,
  即 9007199254740991,能够表示的最小整数是 -(2⁵³ - 1),即 -9007199254740991。

Number can be expressed in octal or hexadecimal
Octal:
Octal:
Use 0 as a prefix

Hexadecimal:
use 0x as prefix

var a = 0322;     
var b = 0xab;   

Infinity (infinity)
Infinity:
positive infinity
-Infinity:
negative infinity

var a = 88 / 0;      // 等于 Infinity
var b = -88 / 0;     // 等于 -Infinity

NaN (not a number)
NaN is a special value in JavaScript
for a value that is not a number
NaN is not equal to (via、!=、=, !=== comparison) any other value (including another NaN value)
use the isNaN() function to determine whether a number is NaN

    parseInt("java")、new Number("java");

任何操作数中包含NaN表达式
   例:
     88 * NaN
   如:
     "java"/5 也可返回NaN

Number property

Number.MAX_VALUE The maximum value that can be expressed
Number.MIN_VALUE The minimum value that can be expressed
Number.NaN Non-number
Number.NEGATIVE_INFINITY Negative infinity, return
Number.POSITIVE_INFINITY positive infinity, return
Number.EPSILON when overflow refers to 1 and Number can
The difference between the smallest floating-point numbers greater than 1.
Number.MIN_SAFE_INTEGER Minimum safe integer, ie -9007199254740991
Number.MAX_SAFE_INTEGER Maximum safe integer, ie 9007199254740991

The Number method
Number.parseFloat() converts a string into a floating point number, which has the same effect as the global method parseFloat()

Number.parseInt() converts a string into an integer number, which has the same effect as the global method parseInt()

Number.isFinite() Determines whether the Number object is a finite number

Number.isInteger() Determines whether the Number object is an integer

Number.isNaN() Determines whether the Number object is of NaN type

Number.isSafeInteger() Determines whether the Number object is a safe integer, that is, an integer ranging from -(2⁵³ - 1) to 2⁵³ - 1

Number.toString() converts a Number object to a string, using the specified radix

Number.toLocaleString() converts a Number object to a string, using the local number format order

Number.toFixed() converts the Number object to a string, and the result has a number of specified digits after the decimal point

Number.toExponential() converts the value of the Number object to exponential notation

Number.toPrecision() Formats the Number object to the specified length

Number.valueOf() Returns the basic numeric value of a Number object

String (string) object

Syntax for String object creation:
var val = new String(value);
var val = String(value);

  value:指待创建的字符串或字符串对象。

Properties in the String object

constructor #Get the reference to the String() function that created this object
length #Get the length of the string
prototype #Through this property, you can add properties and methods to the object

var str = new String('YHW');
String.prototype.name = null;
str.name = "Hello World!";
document.write(str.constructor + "<br>");       // 输出:function String() { [native code] }
document.write(str.length + "<br>");            // 输出:3
document.write(str.name);                       // 输出:YHW

The method anchor() in the String object
creates an HTML anchor point, that is, generates an a tag, and
the name attribute of the tag is the parameter big() in the anchor() method
to display the string in a large font
blink() to display the flashing characters String
bold() Display a string in bold
charAt() Return the character at the specified position
charCodeAt() Return the Unicode code of the specified character
concat() Concatenate the string
fixed() Display the string in typewriter text
fontcolor() Use the specified color To display the string
fontsize() Use the specified size to display the string
fromCharCode() Convert the character code to a string
indexOf() Retrieve the string, get the position of the first occurrence of the given string in the string object
italics() Displays a string in italics
lastIndexOf() Gets the position of the last occurrence of a given string within a string object
link() Displays a string as a link
localeCompare() Returns a number and uses that number to
indicate whether the string object is greater than, Less than or equal to the given string
match() Matches characters in the string according to the regular expression
replace() Replaces the substring matching the regular expression
search() Gets the position of the first occurrence of the string matching the regular expression
slice() intercepts a segment of a string and returns it
small() uses a small font size to display the string
split() splits the string into an array of strings according to the given character
strike() uses a strikethrough to display the string
sub( ) Display the string as a subscript
substr() Intercept a string of the specified length from the specified index position
substring() Intercept the characters between two specified indexes in the string
sup() Display the string as a superscript
toLocaleLowerCase() Convert a string to lowercase
toLocaleUpperCase() Convert a string to uppercase
toLowerCase() Convert a string to lowercase
toUpperCase() Convert a
string to uppercase toString() Return a string
valueOf() Return the original value of a string object value

var str = new String('5天速通JavaScript');
document.write(str.anchor("myanchor") + "<br>");     // 生成一段 HTML 代码:<a name="myanchor">5天速通JavaScript</a>
document.write(str.big() + "<br>");                  // 生成一段 HTML 代码:<big>5天速通JavaScript</big>
document.write(str.blink() + "<br>");                // 生成一段 HTML 代码:<blink>5天速通JavaScript</blink>
document.write(str.bold() + "<br>");                 // 生成一段 HTML 代码:<b>5天速通JavaScript</b>
document.write(str.charAt(2) + "<br>");             // 获取 str 中的第 2 个字符,输出:速
document.write(str.charCodeAt(2) + "<br>");         // 获取 str 中第 2 个字符的 Unicode 编码,输出:36895
document.write(str.concat(" String 对象") + "<br>"); // 将字符串“ String 对象”拼接到字符串 str 之后,输出:5天速通JavaScript String 对象
document.write(str.fixed() + "<br>");                // 生成一段 HTML 代码:<tt>5天速通JavaScript</tt>
document.write(str.fontcolor("red") + "<br>");       // 生成一段 HTML 代码:<font color="red">5天速通JavaScript</font>
document.write(str.fontsize(2) + "<br>");            // 生成一段 HTML 代码:<font size="2">5天速通JavaScript</font>
document.write(String.fromCharCode(72,69,76,76,79) + "<br>");             // 将 Unicode 编码转换为具体的字符,输出:HELLO
document.write(str.indexOf("Script") + "<br>");             // 获取字符串“Script”在 str 中首次出现的为,输出:8
document.write(str.italics() + "<br>");                     // 生成一段 HTML 代码:<i>5天速通JavaScript</i>
document.write(str.lastIndexOf("a") + "<br>");              // 获取字符串“a”在 str 中最后一次出现的位置,输出 7
document.write(str.link("http://c.biancheng.net/") + "<br>");  // 生成一段 HTML 代码:<a href="http://c.biancheng.net/">5天速通JavaScript</a>
document.write(str.localeCompare("JavaScript") + "<br>");       // 比较字符串对象与给定字符串,返回:-1
document.write(str.match(/[abc]/g) + "<br>");                   // 根据正则 /[abc]/g 检索 str,返回:a,a,c
document.write(str.replace(/[abc]/g, "Y") + "<br>");            // 使用字符串“Y”替换正则 /[abc]/g 匹配的字符,返回:5天速通JYvYSYript
document.write(str.search(/[Script]/g) + "<br>");               // 获取与正则匹配的字符串首次出现的位置,返回:8
document.write(str.slice(6,11) + "<br>");           // 截取字符串(获取 str 中第 7 到第 11 个字符),返回:vascr
document.write(str.small() + "<br>");               // 生成一段 HTML 代码:<small>5天速通JavaScript</small>
document.write(str.split("a") + "<br>");            // 根据“a”将字符串 str 拆分为数组,返回:5天速通J,v,Script
document.write(str.strike() + "<br>");              // 生成一段 HTML 代码:<strike>5天速通JavaScript</strike>
document.write(str.sub() + "<br>");                 // 生成一段 HTML 代码:<sub>5天速通JavaScript</sub>
document.write(str.substr(3, 7) + "<br>");          // 从第 4 个字符开始,向后截取 7 个字符,返回:通JavaSc
document.write(str.substring(3, 7) + "<br>");       // 截取字符串(获取 str 中第 4 到第 7 个字符),返回:通Jav
document.write(str.sup() + "<br>");                 // 生成一段 HTML 代码:<sup>5天速通JavaScript</sup>
document.write(str.toLocaleLowerCase() + "<br>");   // 返回:5天速通JavaScript
document.write(str.toLocaleUpperCase() + "<br>");   // 返回:5天速通JAVASCRIPT
document.write(str.toLowerCase() + "<br>");         // 返回:5天速通JavaScript
document.write(str.toUpperCase() + "<br>");         // 返回:5天速通JAVASCRIPT
document.write(str.toString() + "<br>");            // 返回:5天速通JavaScript
document.write(str.valueOf() + "<br>");             // 返回:5天速通JavaScript

Array (array) object

Each value in the array is called an element
Each element has a numerical position in the array, called the index
The index of the array starts from 0 and increases in sequence
Syntax

ar arr = new Array(values);
var arr = Array(values);
   values:各元素组成的列表
   元素和元素之间使用逗号分隔
var arrs = new Array("YHW1", "YHW2", "YHW3");
console.log(arrs);  //打印出信息 ["YHW1", "YHW2", "YHW3"]

var arrs = ["YHW1", "YHW2", "YHW3" ];
console.log(arrs);        // 输出:(3) ["YHW1", "YHW2", "YHW3"]

您可以通过数组的索引来访问数组中的各个元素,示例代码如下:
var arrs = ["YHW1", "YHW2", "YHW3"];
document.write(arrs[0] + "<br>");     // 输出:YHW1
document.write(arrs[1] + "<br>");     // 输出:YHW2
document.write(arrs[2] + "<br>");     // 输出:YHW3

The property constructor in the Array object
returns the prototype function that creates the array object
length sets or returns the number of elements in the array
prototype Through this property you can add properties and methods to the object

var users = new Array("YHW1", "YHW2", "YHW3");
Array.prototype.name = null;
users.name = "5天速通JavaScript";
document.write(users.constructor + "<br>");      // 输出:function Array() { [native code]}   具体输出结果取决于users变量的类型和实现,如果users是一个数组,则输出结果应该为function Array() { [native code] },如果users是一个对象,则输出结果应该为function Object() { [native code] }         
document.write(users.length + "<br>");           // 输出:3
document.write(users.name + "<br>");             // 输出:5天速通JavaScript

The method concat() in the Array object
concatenates two or more arrays and returns the result
copyWithin() copies elements from the specified position of the array to another specified position of the array
entries() returns the iterable object of the array
every() detection Whether each element of the numerical element meets the condition
fill() fills the array with a fixed
value filter() detects the numerical element and returns an array of all elements that meet the condition
find() returns the array element that meets the condition of the incoming function
findIndex() Returns the index of the array element that meets the conditions of the passed function.
forEach() Each element of the array executes the callback function once.
From() Creates an array from a given object.
includes() Determines whether an array contains a specified value
indexOf() Search The element in the array, and return its position
isArray() Determine whether the object is an array
join() Put all the elements of the array into a string
keys() Return the iterable object of the array, including the key of the original array (key)
lastIndexOf() Searches for an element in the array and returns its last occurrence
map() Processes each element of the array through the specified function and returns the processed array
pop() Deletes the last element of the array and returns the deleted element
push () Adds one or more elements to the end of the array and returns the length of the array
reduce() Accumulates (from left to right) all elements in the array and returns the result
reduceRight() accumulates (from right to left) all elements in the array and returns the result
reverse() reverses the order of the elements in the array
shift() removes and returns the first element of the array
slice() intercepts a portion of the array and Return this new array
some() Check if there are elements in the array elements that meet the specified conditions
sort() Sort the elements of the array
splice() Add or remove elements from the array
toString() Convert the array to a string and return the result
unshift() adds one or more elements to the beginning of the array and returns the length of the new array
valueOf() returns the original value of the array object


var users = ["YHW1", "YHW2", "YHW3", "YHW4", "YHW5"];
document.write(users.entries() + "<br>");              // 返回:[object Array Iterator]
document.write(users.includes("YHW1") + "<br>");      // 返回:true
document.write(users.fill("小傻瓜") + "<br>");          // 返回:小傻瓜,小傻瓜,小傻瓜,小傻瓜,小傻瓜
var users = ["YHW1", "YHW2", "YHW3", "YHW4", "YHW5"];
document.write(users.indexOf("YHW5") + "<br>");               // 返回:4
document.write(Array.isArray(users) + "<br>");                 // 返回:true
document.write(users.join("-") + "<br>");                      // 返回:YHW1-YHW2-YHW3-YHW4-YHW5
document.write(users.lastIndexOf("YHW2") + "<br>");          // 返回:1
document.write(users.pop() + "<br>");                          // 返回:YHW5
document.write(users.push("水葫芦") + "<br>");             // 返回:6
document.write(users.unshift("李四","张三") + "<br>");   // 返回:8
document.write(users.slice(1, 5) + "<br>");                    // 返回:张三,YHW1,YHW2,YHW3
document.write(users.sort() + "<br>");                         // 返回:YHW1,YHW2,YHW3,YHW4,YHW5,张三,李四,水葫芦
document.write(users.valueOf() + "<br>");                      // 返回:YHW1,YHW2,YHW3,YHW4,YHW5,张三,李四,水葫芦

Date (date/time) object

Use this object to access the time of the computer system
Date object provides a variety of methods for manipulating date and time

Methods of creating Date objects
Four ways to create Date objects

var time = new Date();
var time = new Date(milliseconds);
var time = new Date(datestring);
var time = new Date(year, month, date[, hour, minute, second, millisecond]);
使用具年月日、时分秒生成Date对象:
   year:年,笔者推荐使用四位数字年份
   month:月,0代表1月,1代表2月,以此类推;
   date:月份中的某一天,1代表 1号,2代表2号,以此类推
   hour:时,是使用24 小时制表示,取值范围为 0 ~ 23
   minute:分,取值范围为 0 ~ 59;
   second:秒,取值范围为 0 ~ 59;
   millisecond:毫秒,取值范围为 0 ~ 999 

The attribute constructor in the Date object
returns the prototype function
prototype that creates the Date object. Through this attribute, you can add attributes and methods to the object.

var time = new Date();
Date.prototype.name = null;
time.name = "JavaScript";
document.write(time.constructor + "<br>");      // 输出:function Date() { [native code] }
document.write(time.name + "<br>");             // 输出:JavaScript

The method getDate() in the
Date object returns the day of the month (1 ~ 31) from the Date object.
getDay() returns the day of the week (0 ~ 6) from the Date object.
getMonth() returns the month (0 ~ 6) from the Date object 11)
getFullYear() returns the four-digit year from the Date object
getYear() is deprecated, please use the getFullYear() method instead of
getHours() to return the hour of the Date object (0 ~ 23)
getMinutes() returns the minute of the Date object (0 ~ 59)
getSeconds() returns the seconds of the Date object (0 ~ 59)
getMilliseconds() returns the milliseconds of the Date object (0 ~ 999)
getTime() returns the milliseconds from January 1, 1970 to the present
getTimezoneOffset() returns the local time Minute difference from Greenwich Mean Time (GMT)
getUTCDate() Returns the day of the month (1 ~ 31) from a Date object according to universal time
getUTCDay() Returns the day of the week (0 ~ 6) from a Date object according to universal time
getUTCMonth() Returns the month from a Date object according to universal time (0 ~ 11)
getUTCFullYear() Returns the four-digit year from a Date object according to universal time
getUTCHours() Returns the hour of a Date object according to universal time (0 ~ 23)
getUTCMinutes() Returns the minutes of a Date object according to universal time (0 ~ 59)
getUTCSeconds() Returns the seconds of a Date object according to universal time (0 ~ 59)
getUTCMilliseconds() Returns the milliseconds of a Date object according to universal time (0 ~ 999)
parse () Return the number of milliseconds from midnight on January 1, 1970 to the specified date (string)
setDate() Set the day of the month in the Date object (1 ~ 31)
setMonth() Set the month in the Date object (0 ~ 11)
setFullYear () Set the year in the Date object (four digits)
setYear() is obsolete, please use the setFullYear() method instead of
setHours() Set the hour in the Date object (0 ~ 23)
setMinutes() Set the minute in the Date object ( 0 ~ 59)
setSeconds() Set the seconds in the Date object (0 ~ 59)
setMilliseconds() Set the milliseconds in the Date object (0 ~ 999)
setTime() Set the Date object in milliseconds
setUTCDate() Set the Date object according to universal time One day of the month (1 ~ 31)
setUTCMonth() Set the month in the Date object according to the universal time (0 ~ 11)
setUTCFullYear() Set the year in the Date object according to the universal time (four digits)
setUTCHours() Set the hours in a Date object according to universal time (0 ~ 23)
setUTCMinutes() Set the minutes in a Date object according to universal time (0 ~ 59)
setUTCSeconds() Set the seconds in a Date object according to universal time (0 ~ 59) 59)
setUTCMilliseconds() Set the milliseconds in the Date object according to the universal time (0 ~ 999)
toSource() Return the source code of the object
toString() Convert the Date object to a string
toTimeString() Convert the time part of the Date object to a character String
toDateString() Convert the date part of a Date object to a string
toGMTString() Deprecated, please use the toUTCString() method instead of toUTCString
() Convert a Date object to a string
according to universal time toLocaleString() According to the local time format, convert Convert the Date object to a string
toLocaleTimeString() Convert the time part of the Date object to a string according to the local time format
toLocaleDateString() Convert the date part of the Date object to a string according to the local time format
UTC() Return 1970 according to the universal time The number of milliseconds from January 1 of the year to the specified date
valueOf() Returns the original value of the Date object

var time = new Date();
document.write(time.getDate() + "<br>");             
document.write(time.getDay() + "<br>");               
document.write(time.getFullYear() + "<br>");          
document.write(time.getHours() + "<br>");            
document.write(time.getMonth() + "<br>");             
document.write(time.getTime() + "<br>");             
document.write(time.getUTCDate() + "<br>");          
document.write(time.toDateString() + "<br>");        
document.write(time.toString() + "<br>");            
document.write(time.toLocaleDateString() + "<br>");   
document.write(time.toLocaleTimeString() + "<br>");   
document.write(time.toLocaleString() + "<br>");    

Math object

Math is a built-in object in JavaScript.
The Math object provides commonly used information in mathematics,
such as: PI constant value, mathematical function, average number, absolute value, rounding and other operation methods

var pi_val = Math.PI;                 // 数学中 π 的值:3.141592653589793
var abs_val = Math.sin(-5.35);       // -5.35 的绝对值:5.35

E returns the arithmetic constant e, which is the base of the natural logarithm (approximately equal to 2.718)
LN2 returns the natural logarithm of 2 (approximately equal to 0.693)
LN10 returns the natural logarithm of 10 (approximately equal to 2.302)
LOG2E returns the base 2 of e Logarithm (approximately 1.443)
LOG10E Returns the base 10 logarithm of e (approximately 0.434)
PI Returns pi (approximately 3.14159)
SQRT1_2 Returns the reciprocal of the square root of 2 (approximately 0.707)
SQRT2 Returns the square root of 2 (approximately equal to 1.414)

document.write(Math.E + "<br>");            // 输出:2.718281828459045
document.write(Math.LN2 + "<br>");          // 输出:0.6931471805599453
document.write(Math.LN10 + "<br>");         // 输出:2.302585092994046
document.write(Math.LOG2E + "<br>");        // 输出:1.4426950408889634
document.write(Math.LOG10E + "<br>");       // 输出:0.4342944819032518
document.write(Math.PI + "<br>");           // 输出:3.141592653589793
document.write(Math.SQRT1_2 + "<br>");      // 输出:0.7071067811865476
document.write(Math.SQRT2 + "<br>");        // 输出:1.4142135623730951

Method description in the Math object
abs(x) returns the absolute value of x
acos(x) returns the arc cosine of x
acosh(x) returns the arc hyperbolic cosine of x
asin(x) returns the arc sine of x
asinh(x) Returns the inverse hyperbolic sine of x
atan(x) returns the arctangent of x
atanh(x) returns the inverse hyperbolic tangent of x
atan2(y,x) returns the arctangent of y/x cbrt
(x) returns x The cube root of
ceil(x) rounds up x, that is, returns the smallest integer greater than x
clz32(x) returns the number of leading 0s after converting x to 32 unsigned integer numbers
cos(x) returns x The cosine value of
cosh(x) returns the hyperbolic cosine value of x
exp(x) returns the arithmetic constant e to the power of x, that is, Ex
expm1(x) returns the value of exp(x) - 1
floor(x) carries out orientation on x Round down, that is, return the largest integer less than x
fround(x) return the single-precision floating-point number closest to x
hypot([x, [y, […]]]) return the square root of the sum of the squares of all parameters
imul(x, y ) Convert the parameters x and y to 32-bit integers respectively, and return the result of their multiplication
log(x) Return the natural logarithm of x
log1p(x) Return the natural logarithm of x plus 1
log10(x) Returns the base 10 logarithm of x
log2(x) Returns the base 2 logarithm of x
max([x, [y, […]]]) Returns the maximum value
min( [x, [y, […]]]) returns the smallest value among multiple parameters
pow(x,y) returns x raised to the power of y
random() returns a random number between 0 and 1
round(x) returns x The rounded integer
sign(x) Returns the sign of x, that is, whether a number is positive, negative, or 0
sin(x) Returns the sine of x
sinh(x) Returns the hyperbolic sine of x
sqrt(x) Returns the sine of x square root
tan(x) returns the tangent of x
tanh(x) returns the hyperbolic tangent of x
toSource() returns the string "Math"
trunc(x) returns the integer part of x
valueOf() returns the original value of the Math object

document.write(Math.abs(-4.287) + "<br>");              
document.write(Math.acos(0.6) + "<br>");                
document.write(Math.ceil(1.23) + "<br>");               
document.write(Math.exp(1) + "<br>");                  
document.write(Math.floor(4.88) + "<br>");              
document.write(Math.log(8) + "<br>");                   
document.write(Math.max(2, 80, 11, 19) + "<br>");           
document.write(Math.min(2, 80, 11, 19) + "<br>");           
document.write(Math.random() + "<br>");                  
document.write(Math.pow(3, 4) + "<br>");                
document.write(Math.sign(-46) + "<br>");              
document.write(Math.sqrt(234) + "<br>"); 

RegExp (regular expression) object

Regular expression:
It is a formula used to match strings or special characters.
This formula is combined according to the rules of regular expressions to get a regular expression.
In JavaScript, a regular expression consists of two slashes Contains a pattern composition between: /pattern/.
The method of defining a regular expression:
composed of letters, numbers, punctuation and some special characters
such as:

/abc/、/(\d+)\.\d*/

Two methods of the RegExp object:
var patt = new RegExp(pattern, modifiers);
var patt = /pattern/modifiers;

Note:
pattern:
regular expression regular expression
defined according to the syntax of regular expressions
modifiers:
modifiers
are used to set the matching mode of strings.
The optional values ​​are shown in the following table:
pattern: regular expressions
are defined according to the syntax of regular expressions The regular expression
modifiers: Modifiers
are used to set the matching mode of the string

Modifier Description
i performs a case-insensitive match
g performs a global match (finds all matches instead of stopping at the first match found)
m performs a multi-line match
s allows . to match newlines
u uses Unicode Matches the pattern of the code
y Performs a "sticky" search, matching starts at the current position of the target string

When using the new keyword to create a RegExp object,
you need to escape the special characters in the regular expression
, that is, add a backslash \ before the special character, such as \w+.

Description of special characters in regular expressions
.: Matches any single character, but does not match a newline character.
^: Matches the beginning of the input string.
$: Matches the end position of the input string.
*: Matches the preceding subexpression zero or more times.
+: Matches the preceding subexpression one or more times.
?: Matches the preceding subexpression zero or one time.
{n}: Matches the preceding subexpression exactly n times.
{n,}: Matches the preceding subexpression at least n times.
{n,m}: Match the preceding subexpression at least n times, but not more than m times.
[]: Define a character set, match any character in the brackets.
[^]: Define a negative character set, matching any character except the characters in the brackets.
(): Mark the start and end of a subexpression.
|: Indicates a choice between two items.
Use the regular expression
exec() to search for matches in the string and return an array, and
return null when there is no match test () Test whether the string matches the regular expression, return true if it matches, and false if it
does not match
() returns a string representing the specified object

String object

Provides methods to run a regular expression
search() Searches for a match in a string and returns the first matching result
Returns -1 when no match is found match
() Searches for a match in a string and returns an array ,
returns null when there is no match
matchAll() searches for all matches in the string and returns an iterator
replace() replaces the part of the string that matches the regular expression
split() follows the regular expression Split a string into an array of strings

The constructor in the RegExp object
returns a function,
which is a prototype for creating a RegExp object
global Determines whether the modifier "g" is set
ignoreCase Determines whether the modifier "i" is set
lastIndex is used to specify the starting position of the next match
multiline judgment Whether the modifier "m" is set
source returns the matching pattern of the regular expression

var str = "Hello World!";
var reg = /[a-g]/g;
document.write(reg.exec(str) + "<br>");             // 输出:e
document.write(reg.test(str) + "<br>");             // 输出:true
document.write(reg.toString() + "<br>");            // 输出:/[a-g]/g
document.write(str.search(reg) + "<br>");           // 输出:1
document.write(str.match(reg) + "<br>");            // 输出:e,d
document.write(str.matchAll(reg) + "<br>");         // 输出:[object RegExp String Iterator]
document.write(str.replace(reg, "+") + "<br>");     // 输出:H+llo Worl+!
document.write(str.split(reg) + "<br>");            // 输出:H,llo Worl,!

Fifteen, DOM (Document Object Model)

The Document Object Model (DOM for short)
is a platform- and language-independent model
used to represent HTML or XML documents
. The DOM model converts the elements and content in HTML into an object. It is no exaggeration to say: "When the webpage is loaded, the entire HTML content will be converted into a DOM object." We can manipulate the DOM object through JS to achieve the purpose of modifying the HTML content.

始终记住DOM是一个树形结构。操作一个DOM节点实际上就是这么几个操作:
更新:更新该DOM节点的内容,相当于更新了该DOM节点表示的HTML的内容;
遍历:遍历该DOM节点下的子节点,以便进行进一步操作;
添加:在该DOM节点下新增一个子节点,相当于动态增加了一个HTML节点;
删除:将该节点从HTML中删除,相当于删掉了该DOM节点的内容以及它包含的所有子节点。

insert image description here
Generation of Dom
When a browser accesses an html document, it will create a Document object. The Document object is the root node of all nodes in the DOM tree. We can access the Document object to achieve the purpose of accessing all HTML elements.
Node: Node - the most basic unit that constitutes an HTML document
insert image description here
Find HTML elements
insert image description here
Get the value of HTML
insert image description here
Change the value of HTML
insert image description here
Modify HTML elements
insert image description here
Find HTML parent and child
insert image description here

document.addEventListener("click", function(){
    document.body.innerHTML = document.activeElement;
    var box = document.createElement('div');
    document.body.appendChild(box);
    var att = document.createAttribute('id');
    att.value = "myDiv";
    document.getElementsByTagName('div')[0].setAttributeNode(att);
    document.getElementById("myDiv").innerHTML = Math.random();
    var btn = document.createElement("button");
    var t = document.createTextNode("按钮");
    btn.appendChild(t);
    document.body.appendChild(btn);
    var att = document.createAttribute('onclick');
    att.value = "myfunction()";
    document.getElementsByTagName('button')[0].setAttributeNode(att);
});
function myfunction(){
    alert(document.title);
}

Element object

In DOM (Document Object Model), all HTML tags can be expressed as an Element object.
The acquisition method of the Element object:
getElementsByTagName(), getElementById(), getElementsByClassName() and other
attributes in the Element object

element.accessKey	设置或返回一个访问单选按钮的快捷键
element.attributes	返回一个元素的属性数组
element.childNodes	返回元素的一个子节点的数组
element.children	返回元素中子元素的集合
element.classList	返回元素中类名组成的对象
element.className	设置或返回元素的 class 属性
element.clientHeight	返回内容的可视高度(不包括边框,边距或滚动条)
element.clientWidth	返回内容的可视宽度(不包括边框,边距或滚动条)
element.contentEditable	设置或返回元素的内容是否可编辑
element.dir	设置或返回一个元素中的文本方向
element.firstChild	返回元素中的第一个子元素
element.id	设置或者返回元素的 id
element.innerHTML	设置或者返回元素的内容
element.isContentEditable	返回元素内容是否可编辑,如果可编辑则返回 true,否则返回 false
element.lang	设置或者返回一个元素的语言
element.lastChild	返回元素的最后一个子元素
element.namespaceURI	返回命名空间的 URI
element.nextSibling	返回指定元素之后的兄弟元素,两个元素在 DOM 树中位于同一层级(包括文本节点、注释节点)
element.nextElementSibling	返回指定元素之后的兄弟元素,两个元素在 DOM 树中位于同一层级(不包括文本节点、注释节点)
element.nodeName	返回元素名称(大写)
element.nodeType	返回元素的节点类型
element.nodeValue	返回元素的节点值
element.offsetHeight	返回元素的高度,包括边框和内边距,但不包括外边距
element.offsetWidth	返回元素的宽度,包括边框和内边距,但不包括外边距
element.offsetLeft	返回元素在水平方向的偏移量
element.offsetParent	返回距离该元素最近的进行过定位的父元素
element.offsetTop	返回元素在垂直方向的偏移量
element.ownerDocument	返回元素的根元素(文档对象)
element.parentNode	返回元素的父节点
element.previousSibling	返回元素之前的兄弟元素,两个元素在 DOM 树中位于同一层级(包括文本节点、注释节点)
element.previousElementSibling	返回元素之前的兄弟元素,两个元素在 DOM 树中位于同一层级(不包括文本节点、注释节点)
element.scrollHeight	返回元素的完整高度(包括被滚动条隐蔽的部分)
element.scrollLeft	设置或返回元素滚动条距离元素左侧的距离
element.scrollTop	设置或返回元素滚动条距离元素上方的距离
element.scrollWidth	返回元素的完整宽度(包括被滚动条隐蔽的部分)
element.style	设置或返回元素的样式属性
element.tabIndex	设置或返回元素的标签顺序
element.tagName	以字符的形式返回元素的名称(大写)
element.textContent	设置或返回某个元素以及其中的文本内容
element.title	设置或返回元素的 title 属性
element.length	返回对象的长度

Method in Element object

element.addEventListener()	为指定元素定义事件
element.appendChild()	为元素添加一个新的子元素
element.cloneNode()	克隆某个元素
element.compareDocumentPosition()	比较当前元素与指定元素在文档中的位置,
返回值如下:
1:表示两个元素没有关系,不属于同一文档;
2:表示当前元素在指定元素之后;
4:当前元素在指定元素之前;
8:当前元素在指定元素之内;
16:指定元素在当前元素之内;
32:两个元素没有关系,或者它们是同一元素的两个属性
element.focus()	使元素获得焦点
element.getAttribute()	通过属性名称获取指定元素的属性值
element.getAttributeNode()	通过属性名称获取指定元素得属性节点
element.getElementsByTagName()	通过标签名获取当前元素下的所有子元素的集合
element.getElementsByClassName()	通过类名获取当前元素下的子元素的集合
element.hasAttribute()	判断元素是否具有指定的属性,若存在则返回 true,不存在则返回 false
element.hasAttributes()	判断元素是否存在任何属性,若存在则返回 true,不存在则返回 false
element.hasChildNodes()	判断一个元素是否具有子元素,有则返回 true,没有则返回 false
element.hasFocus()	判断元素是否获得了焦点
element.insertBefore()	在已有子元素之前插入一个新的子元素
element.isDefaultNamespace()	如果指定 namespaceURI 是默认的则返回 true,否则返回 false
element.isEqualNode()	检查两个元素是否相等
element.isSameNode()	检查当前元素与指定元素是否为同一元素
element.isSupported()	判断当前元素是否支持某个特性
element.normalize()	合并相邻的文本节点,并删除空的文本节点
element.querySelector()	根据CSS选择器,返回第一个匹配的元素
document.querySelectorAll()	根据CSS选择器,返回所有匹配的元素
element.removeAttribute()	从元素中删除指定的属性
element.removeAttributeNode()	从元素中删除指定的属性节点
element.removeChild()	删除一个子元素
element.removeEventListener()	移除由 addEventListener() 方法添加的事件
element.replaceChild()	替换一个子元素
element.setAttribute()	设置或者修改指定属性的值
element.setAttributeNode()	设置或者修改指定的属性节点
element.setUserData()	在元素中为指定键值关联对象
element.toString()	将元素转换成字符串
nodelist.item()	返回某个元素基于文档树的索引
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速成JavaScript</title>
</head>
<body onload="accesskey()">
    <a id="r" class="ttt yyy uuu" href="javascript:;">使用 Alt + r 访问该元素</a><br>
    <a id="g" href="javascript:;">使用 Alt + g 访问该元素</a>
    <script type="text/javascript">
        function accesskey(){
            document.getElementById('r').accessKey="r"
            document.getElementById('g').accessKey="g"
        }
        var ele = document.getElementById('r');
        console.log(ele.attributes);                            // 输出:NamedNodeMap {0: id, 1: href, id: id, href: href, length: 2}
        console.log(document.body.childNodes);                  // 输出:NodeList(7) [text, a#r, br, text, a#g, text, script]
        console.log(ele.classList);                             // 输出:DOMTokenList(3) ["ttt", "yyy", "uuu", value: "ttt yyy uuu"]
        console.log(ele.className);                             // 输出:aaa bbb ccc
        console.log(ele.clientHeight);                          // 输出:DOMTokenList(3) ["ttt", "yyy", "uuu", value: "ttt yyy uuu"]
        console.log(ele.tagName);                               // 输出:A
        console.log(ele.compareDocumentPosition(document.getElementById('g')));     // 输出:4
        console.log(ele.getAttribute('href'));                  // 输出:javascript:;
        console.log(ele.getAttributeNode('href'));              // 输出:href="javascript:;"
    </script>
</body>
</html>

attributes object

Attributes object:
Contains the attributes of the element object and the attributes of the element that can be manipulated through this object,
such as: adding, deleting, and modifying the attributes of the html element.
insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速成JavaScript</title>
</head>
<body>
    <a href="javascript:;" target="_blank" id="linkTest">JavaScript</a><br>
    <script type="text/javascript">
        var atag = document.getElementById('linkTest');
        var attr = atag.attributes;
        document.write(attr.target.value + "<br>");                 // 输出:_blank
        document.write(attr.target.name + "<br>");                  // 输出:target
        document.write(attr.target.specified + "<br>");             // 输出:true
        document.write(attr.getNamedItem('href').textContent + "<br>");  // 输出:javascript:;
        document.write(attr.item(0).name + "<br>");                 // 输出:href
        document.write(attr.length + "<br>");                       // 输出:3
        document.write(attr.removeNamedItem('target') + "<br>");    // 输出:[object Attr]
        var cla = document.createAttribute('class');
        cla.value = 'democlass';
        document.write(attr.setNamedItem(cla) + "<br>");            // 输出:null
    </script>
</body>
</html> 

Sixteen, BOM (Browser Object Model)

Browser Object Model (Browser Object Model, referred to as BOM) is one of the components of JavaScript. With the help of BOM, JavaScript programs can interact with browsers.
Window: represents the window of the entire browser, and window is also a global object in the web page.
Navigator: represents the information of the current browser, through which different browsers can be identified.
Location: represents the address bar information of the current browser, You can obtain address bar information through Location, or operate the browser to jump to the page.
History: represents the history of the browser. You can use this object to operate the history of the browser. Due to privacy reasons, this object cannot obtain specific history. You can only operate the browser to turn pages forward or backward, and this operation is only valid during the current visit.
Screen: Represents the information of the user's screen, through which the relevant information of the user's display can be obtained.

Window object

JavaScript has three types of popups: alerts, confirmations, and tooltips.
warning box

window.alert("sometext");

confirmation box

window.confirm("sometext");

例
var r = confirm("请按按钮");
if (r == true) {
    x = "您按了确认!";
} else {
    x = "您按了取消!";
}

prompt box

window.prompt("sometext","defaultText");

var person = prompt("请输入您的姓名", "比尔盖茨");
if (person != null) {
    console.log(person);
}


Common properties in the window object

closed	返回窗口是否已被关闭
defaultStatus	设置或返回窗口状态栏中的默认文本
document	对 Document 对象的只读引用
frames	返回窗口中所有已经命名的框架集合,集合由 Window 对象组成,每个 Window 对象在窗口中含有一个 <frame> 或 <iframe> 标签
history	对History 对象的只读引用,该对象中包含了用户在浏览器中访问过的 URL
innerHeight	返回浏览器窗口的高度,不包含工具栏与滚动条
innerWidth	返回浏览器窗口的宽度,不包含工具栏与滚动条
localStorage	在浏览器中以键值对的形式保存某些数据,保存的数据没有过期时间,会永久保存在浏览器中,直至手动删除
length	返回当前窗口中 <iframe> 框架的数量
location	引用窗口或框架的 Location 对象,该对象中包含当前 URL 的有关信息
name	设置或返回窗口的名称
navigator	对 Navigator 对象的只读引用,该对象中包含当前浏览器的有关信息
opener	返回对创建此窗口的 window 对象的引用
outerHeight	返回浏览器窗口的完整高度,包含工具栏与滚动条
outerWidth	返回浏览器窗口的完整宽度,包含工具栏与滚动条
pageXOffset	设置或返回当前页面相对于浏览器窗口左上角沿水平方向滚动的距离
pageYOffset	设置或返回当前页面相对于浏览器窗口左上角沿垂直方向滚动的距离
parent	返回父窗口
screen	对Screen 对象的只读引用,该对象中包含计算机屏幕的相关信息
screenLeft	返回浏览器窗口相对于计算机屏幕的 X 坐标
screenTop	返回浏览器窗口相对于计算机屏幕的 Y 坐标
screenX	返回浏览器窗口相对于计算机屏幕的 X 坐标
sessionStorage	在浏览器中以键值对的形式存储一些数据,数据会在关闭浏览器窗口或标签页之后删除
screenY	返回浏览器窗口相对于计算机屏幕的 Y 坐标
self	返回对 window 对象的引用
status	设置窗口状态栏的文本
top	返回最顶层的父窗口
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速成JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        window.defaultStatus = "JavaScript"
        document.write(window.defaultStatus + "<br>");    // 输出:JavaScript
        document.write(window.innerHeight + "<br>");      // 输出:314
        document.write(window.innerWidth + "<br>");       // 输出:539
        document.write(window.length + "<br>");           // 输出:0
        document.write(window.location + "<br>");         // 输出:file:///D:/test/js.html
        document.write(window.opener + "<br>");           // 输出:null
        document.write(window.outerHeight + "<br>");      // 输出:558
        document.write(window.outerWidth + "<br>");       // 输出:555
        document.write(window.parent + "<br>");           // 输出:[object Window]
        document.write(window.screenLeft + "<br>");       // 输出:2263
        document.write(window.screenTop + "<br>");        // 输出:401
        document.write(window.screenX + "<br>");          // 输出:2263
        document.write(window.screenY + "<br>");          // 输出:401
    </script>
</body>
</html>

method in window object

alert()	在浏览器窗口中弹出一个提示框,提示框中有一个确认按钮
atob()	解码一个 base-64 编码的字符串
btoa()	创建一个 base-64 编码的字符串
blur()	把键盘焦点从顶层窗口移开
clearInterval()	取消由 setInterval() 方法设置的定时器
clearTimeout()	取消由 setTimeout() 方法设置的定时器
close()	关闭某个浏览器窗口
confirm()	在浏览器中弹出一个对话框,对话框带有一个确认按钮和一个取消按钮
createPopup()	创建一个弹出窗口,注意:只有 IE 浏览器支持该方法
focus()	使一个窗口获得焦点
getSelection()	返回一个 Selection 对象,对象中包含用户选中的文本或光标当前的位置
getComputedStyle()	获取指定元素的 CSS 样式
matchMedia()	返回一个 MediaQueryList 对象,表示指定的媒体查询解析后的结果
moveBy()	将浏览器窗口移动指定的像素
moveTo()	将浏览器窗口移动到一个指定的坐标
open()	打开一个新的浏览器窗口或查找一个已命名的窗口
print()	打印当前窗口的内容
prompt()	显示一个可供用户输入的对话框
resizeBy()	按照指定的像素调整窗口的大小,即将窗口的尺寸增加或减少指定的像素
resizeTo()	将窗口的大小调整到指定的宽度和高度
scroll()	已废弃。您可以使用 scrollTo() 方法来替代
scrollBy()	将窗口的内容滚动指定的像素
scrollTo()	将窗口的内容滚动到指定的坐标
setInterval()	创建一个定时器,按照指定的时长(以毫秒计)来不断调用指定的函数或表达式
setTimeout()	创建一个定时器,在经过指定的时长(以毫秒计)后调用指定函数或表达式,只执行一次
stop()	停止页面载入
postMessage()	安全地实现跨源通信
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com -JavaScript</title>
</head>
<body>
    <p id="show_tag">此处显示点击按钮的效果</p>
    <button onclick="myBtoa()">btoa()</button>
    <button onclick="myAtob()">atob()</button>
    <button onclick="myAlert()">alert()</button>
    <button onclick="myConfirm()">confirm()</button>
    <button onclick="myOpen()">open()</button>
    <button onclick="myMoveBy()">moveBy()</button>
    <button onclick="myMoveTo()">moveTo()</button>
    <button onclick="myPrint()">print()</button>
    <button onclick="myPrompt()">prompt()</button>
    <button onclick="myResizeBy()">resizeBy()</button>
    <button onclick="myClose()">close()</button>
    <script type="text/javascript">
        var ptag = document.getElementById('show_tag');
        var str;
        function myBtoa(){
            str = btoa("JavaScript");
            ptag.innerHTML = str;
        }
        function myAtob(){
            ptag.innerHTML = typeof str;
            if(str == undefined){
                ptag.innerHTML = "请先点击 btoa() 按钮";
                return;
            }
            ptag.innerHTML = atob(str);
        }
        function myAlert(){
            alert("这是一个提示框!");
        }
        function myConfirm(){
            var x;
            var r = confirm("按下按钮!");
            if (r == true){
                x = "你按下了\"确定\"按钮!";
            }
            else{
                x = "你按下了\"取消\"按钮!";
            }
            ptag.innerHTML = x;
        }
        var myWin;
        function myOpen(){
            if(myWin == undefined || (myWin != undefined && myWin.closed == true)){
                myWin = window.open('', '', 'width=200,height=100');
            }else{
                return;
            }
        }
        function myMoveBy(){
            if(myWin == undefined || myWin.closed == true) myOpen();
            myWin.moveBy(200, 200);
        }
        function myMoveTo(){
            if(myWin == undefined || myWin.closed == true) myOpen();
            myWin.moveTo(0, 0);
        }
        function myPrint(){
            print();
        }
        function myPrompt(){
            var name = prompt("请输入你的名字。")
            if (name != null && name != ""){
                ptag.innerHTML = "你好 " + name  + "! 今天感觉如何?";
            } else {
                ptag.innerHTML = "你没有输入任何内容";
            }
        }
        function myResizeBy(){
            if(myWin == undefined || myWin.closed == true) myOpen();
            myWin.resizeBy(100, 100);
        }
        function myClose(){
            if(myWin == undefined) return;
            if(myWin != undefined && myWin.closed == false) myWin.close();
        }
    </script>
</body>
</html>

Navigator object

The function of the Navigator object is used to obtain browser information. The browser information is stored in the Navigator object.
Judgment on browser type:

var ua = navigator.userAgent;
if (/firefox/i.test(ua)) {
    alert("你是火狐浏览器");
} else if (/chrome/i.test(ua)) {
    alert("你是谷歌浏览器");
} else if (/msie/i.test(ua)) {
    alert("你是IE5-IE10浏览器");
} else if ("ActiveXObject" in window) {
    alert("你是IE11浏览器");
}

Properties in the navigator object

appCodeName	返回当前浏览器的内部名称(开发代号)
appName	返回浏览器的官方名称
appVersion	返回浏览器的平台和版本信息
cookieEnabled	返回浏览器是否启用 cookie,启用返回 true,禁用返回 false
onLine	返回浏览器是否联网,联网则返回 true,断网则返回 false
platform	返回浏览器运行的操作系统平台
userAgent	返回浏览器的厂商和版本信息,即浏览器运行的操作系统、浏览器的版本、名称
navigator	对象中的方法

Methods in the navigator object

javaEnabled()	返回浏览器是否支持运行 Java Applet 小程序,支持则返回 true,不支持则返回 false
sendBeacon()	向浏览器异步传输少量数据
document.write("navigator.appCodeName:" + navigator.appCodeName + "<br>");
document.write("navigator.appName:" + navigator.appName + "<br>");
document.write("navigator.appVersion:" + navigator.appVersion + "<br>");
document.write("navigator.cookieEnabled:" + navigator.cookieEnabled + "<br>");
document.write("navigator.onLine:" + navigator.onLine + "<br>");
document.write("navigator.platform:" + navigator.platform + "<br>");
document.write("navigator.userAgent:" + navigator.userAgent + "<br>");
document.write("navigator.javaEnabled():" + navigator.javaEnabled() + "<br>");

Screen object (get screen information)

The screen object has information about the current computer screen,
such as: resolution, width, height, etc.

Method to get the screen object

  window.screen

common attributes

availTop	返回屏幕上方边界的第一个像素点(大多数情况下返回 0)
availLeft	返回屏幕左边边界的第一个像素点(大多数情况下返回 0)
availHeight	返回屏幕的高度(不包括 Windows 任务栏)
availWidth	返回屏幕的宽度(不包括 Windows 任务栏)
colorDepth	返回屏幕的颜色深度(color depth),
根据 CSSOM(CSS 对象模型)视图,为兼容起见,该值总为 24
height	返回屏幕的完整高度
pixelDepth	返回屏幕的位深度/色彩深度(bit depth)
根据 CSSOM(CSS 对象模型)视图
为兼容起见,该值总为 24
width	返回屏幕的完整宽度
orientation	返回当前屏幕的方向
document.write(screen.availTop + "<br>");   // 输出:0
document.write(screen.availLeft + "<br>");  // 输出:0
document.write(screen.availHeight + "<br>");// 输出:1050
document.write(screen.availWidth + "<br>"); // 输出:1920
document.write(screen.height + "<br>");     // 输出:1080
document.write(screen.width + "<br>");      // 输出:1920
document.write(screen.colorDepth + "<br>"); // 输出:24
document.write(screen.pixelDepth + "<br>"); // 输出:24
console.log(screen.orientation);           
 // 输出:ScreenOrientation {angle: 0, type: "landscape-primary", onchange: null}

example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速成JavaScript</title>
</head>
<body>
    <button type="button" onclick="getResolution();">获取屏幕的宽度和高度</button>
    <script type="text/javascript">
        function getResolution() {
            alert("您计算机屏幕的尺寸为:" + screen.width + "x" + screen.height);
        }
    </script>
</body>
</html>

Location object (get URL)

The Location object encapsulates the information in the address bar of the browser (information about the current page link,
such as URL, port, protocol, anchor node information, etc. of the current link), and if you print the location directly, you can get the information in the address bar (current full path to the page)

properties in the location object

console.log(location);          //输出location对象
console.log(location.href);     //输出当前地址的全路径地址
console.log(location.origin);   //输出当前地址的来源
console.log(location.protocol); //输出当前地址的协议
console.log(location.hostname); //输出当前地址的主机名
console.log(location.host);     //输出当前地址的主机
console.log(location.port);     //输出当前地址的端口号
console.log(location.pathname); //输出当前地址的路径部分
console.log(location.search);   //输出当前地址的?后边的参数部分

method in the location object

assign()	加载指定的 URL,即载入指定的文档
reload()	重新加载当前 URL
replace()	用指定 URL 替换当前的文档,与 assign() 方法不同的是,使用 replace() 替换的新页面不会保存在浏览历史中,用户不能使用后退来返回该页面
toString()	与href 属性的效果相同,以字符串的形式返回当前完整的 URL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <a href="https://www.bilibili.com/" id="url"></a>
    <button onclick="myAssign()">assign()</button>
    <button onclick="myReload()">reload()</button>
    <button onclick="myReplace()">replace()</button>
    <button onclick="myToString()">toString()</button>
    <script type="text/javascript">
        var url = 'https://www.bilibili.com';
        function myAssign(){
            location.assign(url);
        }
        function myReload(){
            location.reload();
        }
        function myReplace(){
            location.replace(url);
        }
        function myToString(){
            var url = document.getElementById('url');
            var str = url.toString();
            alert(str);
        }
    </script>
</body>
</html>

History object (get browsing history)

History object: It is used by the browser to store access history information.
The history object will record the pages visited by the current browser.
When there is an iframe page in the page, the history of the window object will also record the history information in the iframe.

Attributes in the history object

length	返回浏览历史的数目,包含当前已经加载的页面
scrollRestoration	利用浏览器特性,使我们在返回上一页或者下一页时,将页面滚动到之前浏览的位置,该属性有两个值,分别是 auto(表示滚动)与 manual(表示不滚动)
state	返回浏览器在当前 URL 下的状态信息,如果没有调用过 pushState() 或 replaceState() 方法,则返回默认值 null

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com-JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        document.write(history.length + "<br>");
        document.write(history.scrollRestoration + "<br>");
        document.write(history.state + "<br>");
    </script>
</body>
</html>

history object

back()	参照当前页面,返回历史记录中的上一条记录(即返回上一页),您也可以通过点击浏览器工具栏中的←按钮来实现同样的效果
forward()	参照当前页面,前往历史记录中的下一条记录(即前进到下一页),您也可以通过点击浏览器工具栏中的→按钮来实现同样的效果
go()	参照当前页面,根据给定参数,打开指定的历史记录,例如 -1 表示返回上一页,1 表示返回下一页
pushState()	向浏览器的历史记录中插入一条新的历史记录
replaceState()	使用指定的数据、名称和 URL 来替换当前历史记录
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速成JavaScript</title>
</head>
<body>
    <button onclick="myBack()">back()</button>
    <button onclick="myForward()">forward()</button>
    <button onclick="myGo()">go()</button>
    <button onclick="myPushState()">pushState()</button>
    <button onclick="myReplaceState()">replaceState()</button>
    <script type="text/javascript">
        function myBack(){
            history.back();
        }
        function myForward(){
            history.forward();
        }
        function myGo(){
            var num = prompt('请输入一个整数', '1');
            history.go(num);
        }
        function myPushState(){
            var state = { 'page_id': 1, 'user_id': 5 }
            var title = 'JavaScript'
            var url = 'index.html'
            history.pushState(state, title, url)
            console.log(history.state);
        }
        function myReplaceState(){
            var state = { 'page_id': 3, 'user_id': 5 }
            var title = 'history'
            var url = 'index.html'
            history.replaceState(state, title, url)
            console.log(history.state);
        }
    </script>
</body>
</html>

Seventeen, timer (setTimeout and setInterval)

avaScript timers: called "timers"
are used to run certain tasks after a specified time, JS timers are time-consuming alarm clocks in our lives.

setTimeout()	在指定的时间后(单位为毫秒)
执行某些代码,代码只会执行一次
setInterval()	按照指定的周期(单位为毫秒)来重复执行某些代码,定时器不会自动停止,除非调用 clearInterval() 函数来手动停止或着关闭浏览器窗口

setTimeout() function syntax format

setTimeout(function[, delay, arg1, arg2, ...]);
setTimeout(function[, delay]);
setTimeout(code[, delay]);
   
参数说明如下:
function:
    一个函数(通常使用匿名函数)
    其中定义了定时器中要执行的代码
code:
    字符串类型的代码
    这些代码会在定时器到期后被编译执行
     出于安全考虑不建议使用;
delay:
    可选参数,定时器在执行的其中代码之前,
	   要等待的时间
	   单位为毫秒(1秒 = 1000毫秒),
	   如果省略此参数,则表示立即执行;
arg1、arg2、...、argN:要传递给函数的参数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速通JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var myTest = function (str = 'JavaScript'){
            document.write(str + "<br>");
        };
        setTimeout(myTest, 500, 'Hello');
        setTimeout(myTest, 1000);
        setTimeout(function(){
            document.write("定时器<br>");
        }, 1500)
        setTimeout("document.write(\"setTimeout()\")", 2000);
    </script>
</body>
</html>

Syntax format of setInterval() function

setInterval(function, delay, [arg1, arg2, ...]);
setInterval(code, delay);
   参数说明如下:
  function:
     一个函数(通常使用匿名函数)
	   其中定义了定时器中要执行的代码;
   code:
      字符串类型的代码
      这些代码会在定时器到期后被编译执行
      出于安全考虑不建议使用;
   delay:
       可选参数
        定时器在执行的其中代码之前
        要等待的时间
        单位为毫秒(1秒 = 1000毫秒)
        如果省略此参数
         则表示立即执行;
    arg1、arg2、...、argN:
	    要传递给函数的参数 

注意事项:
   使用setInterval() 函数定义的定时器不会自动停止
   除非调用clearInterval()函数来手动停止或关闭浏览器窗口
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <p id="one"></p>
    <p id="two"></p>
    <script type="text/javascript">
        var num = 1;
        var myTest = function (){
            document.getElementById('one').innerHTML += num + " ";
            num ++;
        };
        setInterval(myTest, 500);
        setInterval(function(){
            var d = new Date();
            document.getElementById('two').innerHTML = d.toLocaleTimeString();
        }, 1000);
    </script>
</body>
</html>

JS cancel timer

当使用setTimeout()或setInterval()
   设置定时器时
   这两个方法都会产生一个定时器的唯一ID
    ID为一个正整数值
    也被称为“定时器标识符”
	使用这个ID
     我们可以清除ID所对应的定时器

可以使用clearTimeout()或clearInterval()函数
    来分别清除由setTimeout()或setInterval()函数创建的定时器
    调用clearTimeout()或clearInterval()函数需要提供定时器的唯一ID 作为参数

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速通JavaScript</title>
</head>
<body>
    <p>当前时间为:<span id="clock"></span></p>
    <button onclick="stopClock(this);">停止</button><hr>
    <button onclick="delayedAlert(this);">2秒后弹出一个提示框</button>
    <button onclick="clearAlert();">取消</button>
    <script type="text/javascript">
        var intervalID;
        function showTime() {
            var d = new Date();
            document.getElementById("clock").innerHTML = d.toLocaleTimeString();
        }
        function stopClock(e) {
            clearInterval(intervalID);
            e.setAttribute('disabled', true)
        }
        intervalID = setInterval(showTime, 1000);
        var timeoutID;
        var that;
        function delayedAlert(e) {
            that = e;
            timeoutID = setTimeout(showAlert, 2000);
            e.setAttribute('disabled', true)
        }
        function showAlert() {
            alert('这是一个提示框。');
            that.removeAttribute('disabled');
        }
        function clearAlert() {
            clearTimeout(timeoutID);
            that.removeAttribute('disabled');
        }
    </script>
</body>
</html>

Eighteen, JavaScript exception handling

Classification of Error Exceptions in JavaScript

语法错误:
   也称为解析错误
   一般是因为代码存在某些语法错误引起的
    当发生语法错误时,代码会停止运行

运行时错误:
   也称为异常
   发生在程序运行期间
    如:
	   调用未定义的方法
       读取不存在的文件等
       发生运行时错误也会终止代码运行;

逻辑错误:
    逻辑错误常指逻辑错误导致程序运行异常或终止运行

The difference between errors and exceptions in JS

错误(Error):
    常指代码运行之前出现
    在运行JavaScript程序之前
     JavaScript解释器会先对代码进行检查
      如果代码有误,如某些语法错误,浏览器就会报出相应的错误,只有将错误修正后,代码才能运行。

异常(Exception):
     指代码运行中出现
     如:
	   调用某个未定义的方法、读取不存在的文件等
     在出现异常之前
     代码的运行并不受影响
      当出现异常时
      会在浏览器控制台输出错误信息,此时程序也终止运行

JavaScript exception handling

异常处理的功能:
    用于捕捉产生异常的代码
    使整个程序不会因为异常而终止运行
    在JavaScript中,可以使用try catch 语句来捕获异常
   并做出相应处理
   
   try catch语法格式如下所示:
    try {
		// 可能会发生异常的代码
	} catch(error) {
		// 发生异常时要执行的操作
    }

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速通JavaScript</title>
</head>
<body>
    <script>
        try {
            var title = "JavaScript";
            document.write(title);
            // 调用一个未定义的变量
            document.write(str);
            // 若发生错误,则不会执行以下行
            alert("所有语句都已成功执行。");
        } catch(error) {
            // 处理错误
            alert("错误信息: " + error.message);
        }
        // 继续执行下面的代码
        document.write("<p>Hello World!</p>");
    </script>
</body>
</html>

//代码说明
当try语句块中的代码出现异常时
   会创建并抛出一个 Error 对象(如catch(error)中error)
     对象中包含两个属性
        name:错误的类型
        message:对错误的描述信息

The try catch finally statement
adds a finally statement block after the try catch statement, and the code in the finally statement will be executed no matter whether the code in the try statement block is error-prone or not.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com -- JavaScript</title>
</head>
<body>
    <script>
        // 接收用户输入的参数
        var num = prompt("输入一个 0 到 100 的数字");
        // 获取当前时间
        var start = Date.now();
        try {
            if(num > 0 && num <= 100) {
                console.log(Math.pow(num, num)); // 指数幂的基
            } else {
                console.log("输入的值无效!");
            }
        } catch(e) {
            console.log(e.message);
        } finally {
            // 显示执行代码所用的时间
            console.log("代码执行花费了:" + (Date.now() - start) + "ms");
        }
    </script>
</body>
</html>

JS throws an error method
throw expression expression Use the Error() built-in function to throw an error object
JS built-in error type

EvalError	使用 eval() 函数时发出错误,会抛出该错误
InternalError	由 JavaScript 引擎内部错误导致的异常,会抛出该错误
RangeError	范围错误,当使用了超出允许范围的数值时,会抛出该错误
SyntaxError	语法错误,当代码中存在任何语法错误时,会抛出该错误
TypeError	类型错误,当使用的值不是预期类型时,会抛出该错误,例如对数字调用字符串方法,对字符串调用数组方法等
URIError	URI 错误,当使用 URI 相关函数但传入 URI 参数时,会抛出该错误
ReferenceError	参数错误,当尝试使用未定义的变量、函数、对象时,会抛出该错误

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script>
        function squareRoot(number) {
            // 如果数字为负数,则抛出错误
            if(number < 0) {
                throw new Error("抱歉,无法计算负数的平方根!");
            } else {
                console.log(Math.sqrt(number));
            }
        }
        try {
            squareRoot(16);
            squareRoot(625);
            squareRoot(-9);
            squareRoot(100);
            // 若抛出错误,则不会执行下面的行
            console.log("所有函数都执行成功。");
        } catch(e) {
            // 处理错误
            console.log(e.message);
        }
    </script>
</body>
</html>

Nineteen, form validation method

Forms are the basis of interactive pages. All interactive pages use forms for interactive operations,
such as: user name, mobile phone number, password and other forms on the web page. But when we fill in these form information, we need to perform corresponding verification operations For example: the mobile phone number must meet the specifications, and the password must meet the specifications.
The implementation method of form verification:
1. Use Javascript to obtain the page DOM object method to obtain the html element value
2. Use JS grammar to judge empty or regular expression for verification operation
3. Output the element value that does not conform to the rules, and respond to the user The input controls of the prompt
HTML form mainly include the following types:

文本框,对应的 <input type="text"> ,用于输入文本;
口令框,对应的 <input type="password"> ,用于输入口令;
单选框,对应的 <input type="radio"> ,用于选择一项;
复选框,对应的 <input type="checkbox"> ,用于选择多项;
下拉框,对应的 <select> ,用于选择一项;
隐藏文本,对应的 <input type="hidden"> ,用户不可见,但表单提交时会把隐藏文本发送到

server.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速通JavaScript</title>
    <style>
        .error{
            color: red;
        }
        label{
            display: inline-block;
            width: 70px;
            text-align: right;
        }
    </style>
</head>
<body>
    <form onsubmit="return validateForm()" action="" method="post">
        <fieldset>
            <legend>注册:</legend>
            <div class="row">
                <label>用户名:</label>
                <input type="text" name="name">
                <span class="error" id="nameErr"></span>
            </div>
            <div class="row">
                <label>密码:</label>
                <input type="password" name="pwd">
                <span class="error" id="pwdErr"></span>
            </div>
            <div class="row">
                <label>Email:</label>
                <input type="text" name="email">
                <span class="error" id="emailErr"></span>
            </div>
            <div class="row">
                <label>手机号:</label>
                <input type="text" name="mobile" maxlength="11">
                <span class="error" id="mobileErr"></span>
            </div>
            <div class="row">
                <label>验证码:</label>
                <input type="text" name="captcha" maxlength="4"><span id="captcha" onclick="getCaptcha()"></span>
                <span class="error" id="captchaErr"></span>
            </div>
            <div class="row">
                <input type="submit" value="注册">
            </div>
        </fieldset>
    </form>
    <script>
        var captcha = getCaptcha(); // 生成验证码
        // 清空 input 标签后的提示信息
        var tags = document.getElementsByTagName('input');
        for (var i = 0; i < tags.length; i++) {
            tags[i].onchange = function(){
                var idname = this.name + "Err";
                document.getElementById(idname).innerHTML = '';
            }
        }
        // 显示错误消息
        function printError(elemId, hintMsg) {
            document.getElementById(elemId).innerHTML = hintMsg;
        }
        // 验证表单数据
        function validateForm() {
            // 获取表单元素的值
            var name = document.querySelector("input[name='name']").value;
            var pwd = document.querySelector("input[name='pwd']").value;
            var email = document.querySelector("input[name='email']").value;
            var mobile = document.querySelector("input[name='mobile']").value;
            var captcha = document.querySelector("input[name='captcha']").value;
                  
            if(name == "" || name == null){
                printError("nameErr", "用户名不能为空");
                return false;
            }
            if(pwd == "" || pwd == null){
                printError("pwdErr", "密码不能为空");
                return false;
            }
            if(email == "" || email == null){
                printError("emailErr", "邮箱不能为空");
                return false;
            }
            if(mobile == "" || mobile == null){
                printError("mobileErr", "手机号不能为空");
                return false;
            }
            if(captcha == "" || captcha == null){
                printError("captchaErr", "验证码不能为空");
                return false;
            }
        }
        // 获取验证码
        function getCaptcha(){
            var cap = Math.floor(Math.random()*10000).toString();
            if(cap.length != 4) cap += "0";
            captcha = cap;
            document.getElementById("captcha").innerHTML = cap;
        }
    </script>
</body>
</html>

Data Format Verification
Verify Email
Verify Mobile Number

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>5天速通JavaScript</title>
    <style>
        .error{
            color: red;
        }
        label{
            display: inline-block;
            width: 70px;
            text-align: right;
        }
    </style>
</head>
<body>
    <form onsubmit="return validateForm()" action="" method="post">
        <fieldset>
            <legend>注册:</legend>
            <div class="row">
                <label>用户名:</label>
                <input type="text" name="name">
                <span class="error" id="nameErr"></span>
            </div>
            <div class="row">
                <label>密码:</label>
                <input type="password" name="pwd">
                <span class="error" id="pwdErr"></span>
            </div>
            <div class="row">
                <label>Email:</label>
                <input type="text" name="email">
                <span class="error" id="emailErr"></span>
            </div>
            <div class="row">
                <label>手机号:</label>
                <input type="text" name="mobile" maxlength="11">
                <span class="error" id="mobileErr"></span>
            </div>
            <div class="row">
                <label>验证码:</label>
                <input type="text" name="captcha" maxlength="4"><span id="captcha" onclick="getCaptcha()"></span>
                <span class="error" id="captchaErr"></span>
            </div>
            <div class="row">
                <input type="submit" value="注册">
            </div>
        </fieldset>
    </form>
    <script>
        var capCode = getCaptcha(); // 生成验证码
        console.log(capCode);
        // 清空 input 标签后的提示信息
        var tags = document.getElementsByTagName('input');
        for (var i = 0; i < tags.length; i++) {
            tags[i].onchange = function(){
                var idname = this.name + "Err";
                document.getElementById(idname).innerHTML = '';
            }
        }
        // 显示错误消息
        function printError(elemId, hintMsg) {
            document.getElementById(elemId).innerHTML = hintMsg;
        }
        // 验证表单数据
        function validateForm() {
            // 获取表单元素的值
            var name = document.querySelector("input[name='name']").value;
            var pwd = document.querySelector("input[name='pwd']").value;
            var email = document.querySelector("input[name='email']").value;
            var mobile = document.querySelector("input[name='mobile']").value;
            var captcha = document.querySelector("input[name='captcha']").value;
                  
            if(name == "" || name == null){
                printError("nameErr", "用户名不能为空");
                return false;
            }
            if(pwd == "" || pwd == null){
                printError("pwdErr", "密码不能为空");
                return false;
            }
            if(email == "" || email == null){
                printError("emailErr", "邮箱不能为空");
                return false;
            } else {
                var regex = /^\S+@\S+\.\S+$/;
                if(regex.test(email) === false) {
                    printError("emailErr", "请输入正确的邮箱地址");
                    return false;
                }
            }
            if(mobile == "" || mobile == null){
                printError("mobileErr", "手机号不能为空");
                return false;
            } else {
                var regex = /^[1]\d{10}$/;
                if(regex.test(mobile) === false) {
                    printError("mobileErr", "您输入的手机号码有误");
                    return false;
                }
            }
            if(captcha == "" || captcha == null){
                printError("captchaErr", "验证码不能为空");
                return false;
            } else {
                console.log(capCode);
                console.log(captcha);
                if(capCode != captcha){
                    printError("captchaErr", "验证码有误");
                    return false;
                }
            }
        }
        // 获取验证码
        function getCaptcha(){
            var cap = Math.floor(Math.random()*10000).toString();
            if(cap.length != 4) cap += "0";
            document.getElementById("captcha").innerHTML = cap;
            return capCode = cap;
        }
    </script>
</body>
</html>

Twenty, to achieve animation effects

JavaScript implements the essence of animation: modify the style of elements to change the shape of elements to achieve corresponding animation effects. JavaScript animations are often used in conjunction with timers to achieve the effect of animation changes.
Differences Between JavaScript Animations and CSS Animations

JavaScript动画控制能力更强
    可以在动画播放过程中对动画进行控制
    如:
	 开始、暂停、回放、终止、取消等;

JavaScript动画效果比CSS动画更丰富
    如:
	   曲线运动,冲击闪烁,视差滚动等效果
       只有JavaScript 动画才能完成;

CSS动画存在兼容性问题
   而JavaScript大多时候没有兼容性问题

The following are the animation effects of the two js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com -JavaScript</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box {
            width: 200px;
            height: 200px;
            margin-top: 10px;
            background: rgb(43, 221, 255);
            position: relative;
            left: -200px;
            top: 0;
        }
        #box span {
            width: 20px;
            background: rgb(255, 119, 157);
            position: absolute;
            left: 200px;
            top: 75px;
            color: #fff;
            text-align: center;
            cursor: pointer;
            padding: 5px 1px 5px 0;
            border-radius: 0 5px 5px 0;
        }
        #box span:hover {
            background: rgb(255, 84, 137);
        }
    </style>   
</head>
<body>
    <div id="box">
        <span id="share">分享</span>
    </div>
    <script>
        window.onload = function () {
            //动画
            var div = document.getElementById("box");
            var timer = null;
            div.onmouseover = function () {
                startMove(0);
            };
            div.onmouseout = function () {
                startMove(-200);
            };
            function startMove(targetPosition) {
                clearInterval(timer);
                var speed = 0;
                if (targetPosition < 0) {
                    speed = -10;
                } else {
                    speed = 10;
                }
                timer = setInterval(function () {
                    if (div.offsetLeft == targetPosition) {
                        clearInterval(timer);
                    } else {
                        div.style.left = div.offsetLeft + speed + 'px';
                    }
                }, 17);
            }
        };
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com -JavaScript</title>
    <style type="text/css">
        * {
            margin: 0 auto;
            padding: 0;
        }
        ul {
            list-style: none;
        }
        #view {
            position: relative;
            width: 320px;
            height: 120px;
            border: 10px solid #bc8f8f;
            overflow: hidden;
            margin-top: 5px;
        }
        #img_list {
            position: absolute;
            width: 960px;
        }
        #img_list li {
            float: left;
            width: 320px;
            height: 120px;
        }
    </style>
</head>
<body>
    <div id="view">
        <ul id="img_list">
            <li style="background-color: #87ceeb;"></li>
            <li style="background-color: #ff69b4;"></li>
            <li style="background-color: #98fb98;"></li>
        </ul>
    </div>
    <script type="text/javascript">
        var img_list = document.getElementById('img_list');
        setInterval(function() {
            for (var i = 0; i <= 100; i++) {
                (function(pos) {
                    setTimeout(function() {
                        img_list.style.left = - (pos / 100) * 320 + 'px';
                    }, (pos + 1) * 10)
                })(i)
            }
            var current = img_list.children[0];
            setTimeout(function() {
                img_list.appendChild(current);
                img_list.style.left = '0px';
            }, 1100);
        }, 2000);
    </script>
</body>
</html>

21. Closure principle and function

When two functions are nested with each other, the inner function is a closure. Closure
formation conditions.
The inner function needs to be returned by the outer function return.

function test1(){    // 外部函数
    var num = 0;      // 局部变量
    function test2(){   // 内部函数
        num++;                 
        return num;
    }
    return test2;
}
var fun = test1();             // 返回函数 test2

上述代码构成一个闭包
  其实就是函数test2 

closure function

function test1(){    // 外部函数
    var num = 0;      // 局部变量
    function test2(){   // 内部函数
        num++;                 
        return num;
    }
    return test2;
}
var fun = test1(); 
fun();      // 输出:1
fun();      // 输出:2
fun();      // 输出:3
fun();      // 输出:4
num 是外部函数test1()中一个变量 但值在内部函数test2()中被修改函数test2() 每运行一次就会将 num 加 1,根据闭包的特点,函数 test1()中变量num会一直保存在内存中。

Application scenarios of closures
When we need to define variables in some functions and want the variables to reside in memory
without affecting external global variables, we can use closures

function fun1() {
    var a = 2;
    function subFun() {
        a++;
        console.log(a);
    }
    return subFun;
}

var f1 = fun1();
f1();
f1();
console.log("===============");

function fun2() {
    var a = 2;
    function subFun() {
        a--;
        console.log(a);
    }
    return subFun;
}

var f2 = fun2();
f2();
f2();
console.log("===============");

Twenty-two, strict mode (use strict)

Because the JavaScript grammar is not rigorous enough, when using a variable, you can declare it in advance without using the var keyword
(for example:
url = 'https://www.bilibili.com/').
At this time, the JavaScript interpreter will automatically You create this variable
In order to make the code more rigorous, strict mode is introduced in JavaScript
When we use strict mode, those imprecise syntax will no longer be allowed
) This is the origin of strict mode.
Strict mode was introduced in ECMAScript5 (ES5) due to stricter syntax restrictions, code that could run before may not run in strict mode.
The method of enabling strict mode:
just add "use strict"; or 'use strict'; instruction at the beginning of the JavaScript script

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script>
        "use strict";
        x = 'https://www.bilibili.com/'; // 此处报错:Uncaught ReferenceError: x is not defined at index.html:11
        console.log(x);
    </script>
</body>
</html>
如果将"use strict";指令添加到 JavaScript 程序的第一行,则表示整个脚本都会处于严格模式。如果在函数的第一行代码中添加"use strict";,则表示只在该函数中启用严格模式。如下例所示:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script>
        x = 'https://www.linux28.com/';
        console.log(x);
        function sayHello(){
            'use strict';
            str = 'https://www.bilibili.com/'; // 调用 sayHello() 函数在此处报错:Uncaught ReferenceError: str is not defined at sayHello (index.html:14) at index.html:17
            console.log(str);
        }
        sayHello();
    </script>
</body>
</html>


# "use strict";或'use strict';指令只有在整个脚本第一行或函数第一行时才能被识别
    除IE9以及更低的版本外,所有的浏览器都支持该指令 

The difference between strict mode and normal mode

变量必须先声明后使用
在严格模式下,变量必须先通过var、let或const关键字声明,然后才能被使用。如果不先声明就使用变量,会抛出ReferenceError错误。

删除变量或函数会抛出错误
在严格模式下,如果尝试删除一个变量或函数,会抛出语法错误。在普通模式下,这种操作会静默失败,不会抛出错误。

禁止使用未声明的变量
在严格模式下,如果使用未声明的变量,会抛出ReferenceError错误。在普通模式下,这样的操作会创建一个全局变量。

函数必须声明在顶层作用域或函数内部
在严格模式下,函数必须要么声明在顶层作用域,要么声明在函数内部。在普通模式下,可以在代码块中声明函数。

禁止对只读属性赋值
在严格模式下,如果尝试对只读属性进行赋值,会抛出TypeError错误。在普通模式下,这种操作会静默失败。

eval()函数的作用域限制
在严格模式下,eval()函数执行时的作用域限制更为严格,它执行的代码无法访问包含它的函数的作用域变量。在普通模式下,eval()函数执行的代码可以访问包含它的函数的作用域变量。

Twenty-Three, JSON

JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format that is currently widely used
.
Store and represent data in a text format that is completely independent of the programming language.
The simplicity and clear hierarchy make JSON an ideal data interchange language.
It is easy for people to read and write, and it is also easy for machines to parse and generate, and it can effectively improve the efficiency of network transmission.
There are two basic structures in JSON:
arrays and objects

Array:
an ordered list of values
​​Each array starts with a left square bracket [and ends with a right square bracket]
Multiple values ​​are separated by commas
Object:
None composed of several key/value pairs (ie key:value) Ordered collection
Each object starts with a left curly brace { and ends with a right curly brace}
Multiple key/value pairs are separated by commas

Parse JSON data in JavaScript

 将一个字符串转换为JSON对象
转换为JSON对象的方法
     使用JSON.parse(str)方法

Convert data to JSON

将javascript值转换为JSON格式,我们可以使用
 JSON.stringify()方法
var obj = {
    "name": "JavaScript",
    "author": "https://www.bilibili.com/",
    "year": 2023,
    "genre": "Getting Started tutorial",
    "bestseller": true
};
var json = JSON.stringify(obj);
document.write(json);

Twenty-four, cookie operation

A cookie is a file stored on a computer.
Cookies are often used in web sites. When a user visits a website, the user's information will be stored to facilitate interaction with the server and mark the user's identity. The cookie uses key-value pairs to store user information stored on the client.

set cookies

The document.cookie property can be used to create, read, modify and delete cookie information.

cookie read

document.cookie will return all cookies as strings, type format: cookie1=value; cookie2=value; cookie3=value;

document.cookie = "username=zhangsan";
var cookies = document.cookie;
console.log(cookies);

Cookie modification

Using document.cookie to overwrite the old cookie is to modify

document.cookie = "username=zhangsan";
document.cookie = "username=lisi";
var cookies = document.cookie;
console.log(cookies);

Cookie deletion

Deleting cookies is very simple, you just need to set the expires parameter to a previous time, as shown below, set to Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=zhangsan";
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
var cookies = document.cookie;
console.log(cookies);

twenty five, ajax

At the heart of JAX is the XMLHttpRequest object. All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object is used behind the scenes to exchange data with the server, which means that parts of a web page can be updated without reloading the entire page.

grammar

variable = new XMLHttpRequest();

AJAX XMLHttpRequest object method

new XMLHttpRequest()	创建新的 XMLHttpRequest 对象
abort()	取消当前请求
getAllResponseHeaders()	返回头部信息
getResponseHeader()	返回特定的头部信息
open(method, url, async, user, psw)	规定请求method:请求类型 GET 或 POST
url:文件位置
async:true(异步)或 false(同步)
user:可选的用户名称
psw:可选的密码
send()	将请求发送到服务器,用于 GET 请求
send(string)	将请求发送到服务器,用于 POST 请求
setRequestHeader()	向要发送的报头添加标签/值对

AJAX XMLHttpRequest object properties

XMLHttpRequest.onreadystatechange
   指定一个函数(回调函数),当 readyState  的值发生改变时,就会调用这个函数;
XMLHttpRequest.responseText
   请求的响应信息,如果请求未成功或尚未发送请求,则为 null;
XMLHttpRequest.responseType
   一个枚举值,用于指定响应中包含的数据类型;
XMLHttpRequest.responseURL
   返回响应的序列化 URL(与请求的 URL 相同),如果 URL 为空则返回空字符串;
XMLHttpRequest.responseXML
   返回一个包含 HTML 或 XML 的 Document 对象
    若请求未成功、未发送或响应数据无法解析为 XML 或 HTML 则返回 null;
XMLHttpRequest.status
   一个无符号整型数字,表示请求的响应状态码,常见的响应状态码如下所示:
200:请求成功,服务器成功处理了请求;
404:请求失败,服务器未找到请求的页面;
500:服务器暂时不可用。
XMLHttpRequest.statusText 
   一个字符串,表示响应状态的文本信息,例如“OK”或“Not Found”;
XMLHttpRequest.timeout
   一个无符号整型数字,表示请求的超时时间,单位为毫秒
     若超过该时间,请求会自动终止,默认值为 0,表示没有超时时间;
XMLHttpRequest.upload
    返回一个 XMLHttpRequestUpload 对象,用来表示上传的进度。

Twenty-six, event bubbling and event capture

Clicking on an event triggers a series of events upwards at the same time. We call this phenomenon "event bubbling".
Example of event bubbling

<body>
    <div id="wrap">
        <p class="hint">
            <a href="#">Click Me</a>
        </p>
    </div>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com JavaScript</title>
    <style type="text/css">
        div, p, a {
            padding: 15px 30px;
            display: block;
            border: 2px solid #000;
            background: #fff;
        }
    </style>
</head>
<body>
    <div id="wrap">DIV
        <p class="hint">P
            <a href="#">A</a>
        </p>
    </div>
    <script>
        function showTagName() {
            alert("事件捕获: " + this.tagName);
        }
        var elems = document.querySelectorAll("div, p, a");
        for (let elem of elems) {
            elem.addEventListener("click", showTagName, true);
        }
    </script>
</body>
</html>

event bubbling

Event bubbling starts from the target node and goes upwards along the parent node and triggers the event on the parent node until the root node of the document is like a bubble at the bottom of the water, going up all the way.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
    <style type="text/css">
        div, p, a {
            padding: 15px 30px;
            display: block;
            border: 2px solid #000;
            background: #fff;
        }
    </style>
</head>
<body>
    <div onclick="alert('事件冒泡: ' + this.tagName)">DIV
        <p onclick="alert('事件冒泡: ' + this.tagName)">P
            <a href="#" onclick="alert('事件冒泡: ' + this.tagName)">A</a>
        </p>
    </div>
</body>
</html>

prevent event capture and bubbling

The stopPropagation() method is provided in JavaScript to prevent event capture and event bubbling.
grammar:

event.stopPropagation();
    stopPropagation() 会阻止事件捕获和事件冒泡
    但无法阻止标签的默认行为

stopImmediatePropagation()方法

  阻止同一节点的同一事件的其它事件处理程序
    如
	  为某个节点定义了多个点击事件
      当事件触发时,这些事件会按定义顺序依次执行
    当其中一个事件处理程序中使用stopImmediatePropagation()方法
     则剩下的事件处理程序将不再执行 

stopImmediatePropagation() 方法的语法格式如下:
	event.stopImmediatePropagation();

postscript

Special thanks to the relaxed Xiaoxi for the article, the personal information of the old man, and the notes of the mad god.

Guess you like

Origin blog.csdn.net/qq_68890680/article/details/130165452