[Front-end] Quickly master the core knowledge points of JavaScript with zero foundation

Article directory

1. First introduction to JavaScript

1.1. Introduction to JavaScript language

Insert image description here

(1 Introduction

JavaScript is the most popular scripting language on the Internet. This language can be used for HTML and the web, and can be widely used on servers, PCs, laptops, tablets, smartphones and other devices.

JavaScript is a lightweight programming language that is programming code that can be inserted into HTML pages. When JavaScript is inserted into an HTML page, it can be executed by all modern browsers.

(2) Three major parts of Javascript

  • ECMAScript syntax standard: a standardized specification for scripting languages ​​formulated by ECMA.
  • DOM: Manipulate web pages through the Document Object Model (dom).
  • BOM: Manipulate the browser through the browser object model (bom).

(3) JavaScript version and ECMAScript version
Insert image description here

(4) Why JavaScript is a single-threaded engine

JavaScript is single-threaded, which means that it can only do one thing at the same time. Only the previous thing has been executed before the next thing can be executed. As a result, the subsequent code cannot be executed when a time-consuming task is encountered.

Since js is single-threaded (there is only one JS thread running the JS program at any time in a Tab page), it relies on the task queue to execute the js code, so the js engine will always wait for the arrival of tasks in the task queue, and then be processed.

If js is multi-threaded, then there are two events that operate the dom at the same time, one event edits the dom, and the other event deletes the dom, then contradictory instructions will occur at this time.

1.2.JavaScript introduction methods and comments

(1) Introduction method

Internal introduction method

htmlIntroduce tags within bodytags or headtagsscript

Note: The execution order introduced in the two places is different.

  • When introduced in body:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    我是李祥
    <script>
        document.write("我是JS追加的内容")
    </script>
</body>
</html>

Insert image description here

  • When introduced in head:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        document.write("我是JS追加的内容")
    </script>
</head>
<body>
    我是李祥
</body>
</html>

Insert image description here

The reason is that html files are executed sequentially from top to bottom. Since it is executed in a single thread, when rendering the page, try to render the html tag first, and then get the data through js. Prevent clogging.

External introduction method

  • index.js file
document.write("我是JS外部追加的内容")
  • index.html file
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="index.js"></script>
</head>
<body>
    我是李祥
</body>
</html>

Insert image description here

Note: It is recommended to use w3c's standard structure, style, and behavior separation and introduce it externally.

(2) Annotation method

单行://
多行:/* */

There’s not much to say about this, just remember it.

Insert image description here

1.3. Detailed explanation of Javascript variable declaration

(1) Variable declaration

Use var to define variables (es6 syntax: let, const). There will be an article about es6 later. Here we just need to know var first.

  • Combination of declaration and assignment
var name = '李祥';
console.log(name);
  • Declaration and assignment separate
var age;
age = 18;
console.log(age);
  • Declare multiple variables at the same time
var city = "天津市", area = "宝坻区";
console.log(city,area);

Test code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      var name = "李祥";
      console.log(name);
      var age;
      age = 18;
      console.log(age);
      var city = "天津市",
        area = "宝坻区";
      console.log(city, area);
    </script>
  </head>
  <body></body>
</html>

running result:

Insert image description here

(2) Naming rules

Variables in JS are weakly typed and can save all types of data, that is, variables have no type but values ​​have types.

We can use typeof to determine what type a variable is.

var name = "李祥";
console.log(typeof name);

Insert image description here

  • Variable names must start with a letter, underscore " _" or " ". $Other characters can be 字母, _, 美元符号or 数字.
  • Spaces and other punctuation marks are not allowed in variable names, and the first character cannot be a number.
  • Variable names cannot exceed 255 characters in length.
  • Variable names are case-sensitive. (Javascript is a case-sensitive language).
  • Variable names must be placed on the same line.
  • Keywords, reserved words, true, false, and null reserved in scripting languages ​​cannot be used as identifiers.
1.4. Detailed explanation of JavaScript variable promotion

(1) What is variable promotion?

Variable hoisting is considered to be an understanding of the way execution context (especially the creation and execution phases) works in Javascript. The word Hoisting cannot be found in JavaScript documentation prior to the ECMAScript® 2015 Language Specification.

In the literal sense of the concept, "variable hoisting" means that variable and function declarations are physically moved to the front of the code, but this is not accurate. In fact, the location of variable and function declarations in the code will not change, but will be placed in memory during the compilation phase.

Simply put, variable promotion is during the execution of js code. The js engine promotes the declaration part of the variable and the declaration part of the function to the beginning of the code; after the variable is promoted, the variable will be assigned a default value of undefined.

Let's use an example to demonstrate variable promotion.

console.log(name);
var name = "李祥";

According to what we think, an error should be reported, because the name is printed first, and then the name variable is declared.

But the results were beyond our expectations. The console prints undefined.
Insert image description here

The actual code executed is this:

var name;
console.log(name);
name = "李祥";

The variable is declared but not assigned a value, so the default value is undefined, so the printed result is undefined.

(2) Why is there variable promotion?

Variable promotion exists in the running stage of js code. Then js code is the same as other languages. It needs to go through the compilation and execution stages. In the "compilation" stage, js will collect all variable declarations and make the declarations effective in advance. The rest The statements must be interpreted during the execution phase.

(3) Disable variable promotion

The let and const keywords introduced in es6 will form a block-level scope and there will be no variable promotion. They are called temporary dead zones in js .

There will be articles on let and const later. Now you only need to master the let and const keywords to solve the problem of variable promotion.

2.JavaScript basic data types

2.1. Introduction to JavaScript basic data types
Basic data types illustrate default value
Number Numeric type, including integer values ​​and floating point values, such as 21, 0.23 0
Boolean Boolean type, such as true, false, equivalent to 0 or 1 false
String String type, such as "Zhang San" “”
Undefined var a, declares variable a but does not assign a value to a, at this time a=undefined undefined
Null var a = null, declares variable a to be empty null

Values ​​of basic data types are stored in the stack. When a variable is declared, the variable will go to the memory space to find the corresponding value. If the corresponding value is found, the memory address of the value is directly stored in the variable; if not If found, create a new space to store the corresponding value, and store the memory address of the new space in the variable. In js, variables do not store any value, but the memory address of the value. Once a basic data type is created, it is immutable because the space it occupies is fixed. Modifying the value of a variable is equivalent to re-creating a memory space, and the variable points to the address of the memory space.
Insert image description here

2.2.Basic type data-Number

(1) Statement definition

//字面量声明
var num = 1;
console.log(typeof num);  

Insert image description here

//数字对象方式声明
var xd = new Number(2);
console.log(xd+3); //5

Insert image description here

(2) Determine whether it is an integer

console.log(Number.isInteger(1.3)); //false

Insert image description here

(3) Specify the number of decimal places returned and how many decimal points should be retained

console.log((12.345).toFixed(2)); //12.35

Insert image description here

(4) NaN- represents a non-numeric value, used to determine whether it is a number

isNaN() //用来判断一个值是不是数字
// 如果该值转换为number等于 NaN,则此函数返回 true,可以转化成数字的字符串也被认为是数字。

注意:null, "" 两个值会被判断为数字,所以使用前应该屏蔽
console.log(isNaN('11'));

Insert image description here

console.log(isNaN('11s'));

Insert image description here

(5) Floating point precision

js language has precision error problem when calculating floating point numbers.

var num = 0.1 + 0.2;
console.log(num);

Insert image description here

To solve the problem of accuracy, you can use the method of retaining several decimal places.

var num = 0.1 + 0.2;
console.log(num.toFixed(1))

Insert image description here

2.3.Basic type data-String

(1) String declaration definition

//字面量声明,可以使用单引号或者双引号
var name = '李祥';
console.log(name);

//字符串对象方式声明
var name = new String('李祥');
console.log(name);

Insert image description here

(2) String connection

//连接运算符
var name = "李祥",
info = "是一个软件工程师。";
console.log(name + info);

Insert image description here

(3) Get the string length

var name = "李祥"
console.log(name.length);

Insert image description here

(4) Case conversion

console.log('小写转大写:'+'lixiang'.toUpperCase());
console.log('大写转小写:'+'LIXIANG'.toLowerCase());

Insert image description here

(5) Remove the spaces at both ends of the string. Note that the spaces in the middle of the string cannot be removed.

var str = '   li xiang  ';
console.log(str.length);
console.log(str.trim().length);

Insert image description here

(6) Get a single character in the string

//两种写法获取的值相同
console.log('lixiang'.charAt(3)) 
console.log('lixiang'[3])

Insert image description here

(7) Intercept the string, close the left and open the right

var n = 'lixiang'.slice(1,5);
console.log(n);

Insert image description here

(8) Find string

console.log('lixiang'.indexOf('s')); //5
console.log('lixiang'.indexOf('s', 6)); //6 从第6个字符开始搜索(包含第6个)

Insert image description here

(9) Replace string

var name = "李祥";
var changeName = name.replace("祥", "二祥");
console.log(changeName); //李二祥

Insert image description here

(10) String cutting and splicing

var date = '2023-08-28';
console.log(date.split('-')); //['2023', '08', '28']

var a = date.split('-');
console.log(a.join('/')); //2023/08/28

Insert image description here

2.4.Basic type data-Boolean

(1) Define Boolean type

//字面量声明
var flag =true;
console.log(flag);

Insert image description here

(2) Implicit conversion

几乎所有的类型都可以隐式转换为 Boolean 类型 

    				true						false
String		 非空字符串				空字符串
Number		 非0的数值				 0/NaN
Array	  	 数组不参与比较时		参与比较的空数组
Object		 ✅	
undefined	 								  ✅
null	                      ✅	
NaN													✅

When comparing other types with the Boolean type, the other types will be converted into numerical types before comparison.

(3) Display conversion

var str = '';
console.log(!!str); //false

var num = 0;
console.log(!!num); //false

var obj = null;
console.log(!!obj); //false

Insert image description here

2.5.Basic type data-Undefined

Undefined is a variable that already exists but has no value assigned. Javascript will give this existing variable a default value of undefined.

// 变量被声明了,但没有赋值时,就等于undefined
var i;   // i undefined
console.log(i);

// 对象没有赋值的属性,该属性的值为undefined
var  o = new Object();  // o.p undefined
console.log(o.p);

// 函数没有返回值时,默认返回undefined
var x = f(); //x  undefined
console.log(x);
function f(){
    
    }

Insert image description here

2.6.Basic type data-Null
null表示"没有对象",即该处不应该有值。

用法:
(1) 作为函数的参数,表示该函数的参数不是对象
(2) 作为对象原型链的终点
Object.getPrototypeOf(Object.prototype);
2.7.Basic type data-Symbol

Symbol is a new primitive data type introduced in ES6 to represent unique values.

Symbol values ​​are generated through the Symbol function. This means that the object's attribute name can now have two types, one is the original string, and the other is the new Symbol type. All attribute names belonging to the Symbol type are unique and can be guaranteed not to conflict with other attribute names.

<script>
  var x = {
    
    a:'1'}
  var a = Symbol('a');
  x[a] = '2'
  console.log(x);
</script>

Insert image description here

3.JavaScript object data types

1.Basic form of Javascript object

create an object

var car = {
    
    
  color: 'red', //键值对
  height: 1.8,
  start: function () {
    
    
    console.log('‘启动');
  },

  stop: function () {
    
    
    console.log('熄火');
  },
  suv: true,
  luntai:[1,2,3,4]
};

Insert image description here

Call a method in an object

car.start()

Insert image description here

Get the properties of an object

car.suv

Insert image description here

2. Conventional operations in js objects

(1) Add/modify attributes in the object

console.log(car);
car.pinpai='mg7';
console.log(car);

Insert image description here

console.log(car);
car.pinpai='保时捷';
console.log(car);

Insert image description here

(2) Delete using delete operator

console.log(car);
delete car.pinpai;
console.log(car);

Insert image description here

(3) Query the attributes in the object

  • Object properties can be accessed through the "." operator
  • "[]" operator access, "[]" writes a string
console.log(car.color);
console.log(car['height']);

Insert image description here

3. This accesses its own properties in js
  • Through thiswe can access the properties and methods of the object itself
var person = {
    
    
 name: 'lixiang',
 sayHello: function() {
    
    
  console.log('Hello, I am ' + this.name)
 }
}
person.sayHello();

Insert image description here

4. How to create objects in js

(1) Literal method

  • Declare an object and assign it to a variable
var person = {
    
    
 name: 'lixiang',
 age: 18,
 sex: 1
}

(2) Custom constructor method

  • Fixed parameter application scenarios
function Person(name, age, sex) {
    
    
  this.name = name;
  this.age = age;
  this.sex = sex;
}
var person = new Person('lixiang',18,1);
console.log(person);

Insert image description here

  • Object type parameters
function Person(obj) {
    
    
  this.name = obj.name;
  this.age = obj.age;
  this.sex = obj.sex;
}
var person = new Person({
    
    name:'lixiang',age:18,sex:1});
console.log(person);

Insert image description here

4.JavaScript array data structure

1. How to create arrays in js

Definition of array: An array is a list object. Its prototype provides related operations for traversing and modifying elements. The length and element type of a JavaScript array are not fixed.

Different from Java, the array length in js is dynamically controlled, including the element type, which is not unique.

How to declare an array

// 字面量形式
var arr1=[1,2,true,'lx']


// 构造函数声明
var arr2=new Array(1,2,true,'lx')

Insert image description here

2. Basic methods of operating arrays

(1) Add an element to the array

  • Add subscript method
var arr = [1, 2, true, "lx"];
console.log(arr);
arr[4]=false;
console.log(arr);

Insert image description here

  • Insert a piece of data after the array
var arr = [1, 2, true, "lx"];
console.log(arr);
arr.push(0);
console.log(arr);

Insert image description here

  • Insert a piece of data into the first bit of the array
var arr = [1, 2, true, "lx"];
console.log(arr);
arr.unshift(0);
console.log(arr);

Insert image description here

(2) Delete an element from the array

  • The last element in the array is deleted
var arr = [1, 2, true, "lx"];
console.log(arr);
arr.pop();
console.log(arr);

Insert image description here

  • The first element in the array is deleted
var arr = [1, 2, true, "lx"];
console.log(arr);
arr.shift();
console.log(arr);

Insert image description here

(3) Modify the elements in the array

  • Subscript method modification
var arr = [1, 2, true, "lx"];
console.log(arr);
arr[1]=3;
console.log(arr);

Insert image description here

(4) Query the elements in the array

  • Query by subscript
var arr = [1, 2, true, "lx"];
console.log(arr[1]);

Insert image description here

3. Advanced operations on arrays

(1) splice method

  • Used to delete or replace elements
  • The function has a return value, and what is returned is the deleted element.
  • This method will also change the original array
list.splice(2, 2, 'hello','lx')
// 第⼀个参数是控制从第几位(包含)开始删除或者替换(得看第三个参数有没有值)
// 第⼆个参数控制删除的数量
// 第三个参数将删除了的元素替换掉,可⽤逗号隔开
  • scenes to be used

    • Replace elements in an array

    • Delete part of the array

    • The role of cleared arrays

var arr1=[1,2,3,4]
arr1.splice(2, 2, 'hello','lx')
console.log(arr1);

Insert image description here

(2) How to join

  • Convert array type data to string
  • The difference from toString can be separated by custom symbols between custom elements.
var list=[1,2,3,4]
console.log(list.join(','))

Insert image description here

(3) concat method

  • Used to join two or more arrays
  • Does not change the existing array, but returns a new array containing the values ​​of the concatenated array
var arr1=[1,2,3,4]
var arr2=[5,6,7,8]
var arr3 = arr1.concat(arr2);
console.log(arr3);

Insert image description here

5.Operators and flow control in JavaScript

1. Common operators

(1) Assignment operator =

var name = '李祥';
console.log(name);

Insert image description here

(2) Arithmetic operators

  • * remaining method
var num = 2 * 4;
console.log(num);

Insert image description here

  • /division
var num = 4 / 2;
console.log(num);

Insert image description here

  • +addition
var num = 4 + 2;
console.log(num);

Insert image description here

var name = 'li' + 'xiang';
console.log(name);

Insert image description here

var arr1 = [1,2,3,4];
console.log(1+arr1);

Insert image description here

  • -Subtraction
var num = 6 - 4;
console.log(num);

Insert image description here

  • %remainder
var num = 6 % 4;
console.log(num);

Insert image description here

(3) Auto-increment and auto-decrement operators

  • ++, -- The preceding operation will be executed first in the expression
var x = 1;
++x;
console.log(x);
--x;
console.log(x);

Insert image description here

var y = 2;
var f = 30 + ++y;
console.log(y);
console.log(f);

Insert image description here

  • ++, -- The following operations will be executed at the end of the expression
var y = 2;
var f = 30 + y++;
console.log(y);
console.log(f);

Insert image description here

2. Comparison and logical operators

(1) Comparison operator

operator illustrate
> more than the
< less than
>= greater than or equal to
<= less than or equal to
== Cast comparison
=== No cast comparison

(2) Logical operators

  • Logical AND &&: When the expression on the left side of the operator is false, the current value is returned immediately; when the expression on the left side is true, the value on the right side is returned immediately.

  • Logical OR ||: When one of the two sides of the operator is true, the value of true is returned, otherwise it is false.

  • priority

//&& 的优先级高所以结果是 true
console.log(true || false && false);

//用 () 来提高优先级 
console.log((true || false) && false);
3.if, if/else, ternary expression

(1) if executes the code block when the condition is true

//当条件为真时执行表达式代码块
if (){
    
      //表达式或者变量=》布尔值
  //条件为 true 时执行
}

//如果只有一条代码块,可以不用写 {}
if () console.log(xx)
var x = 2;
if(x===2){
    
    
  console.log('x为2')
}

Insert image description here

(2) if/else executes the if code block when the condition is true, otherwise executes the else code block

if (){
    
    
  //条件为 true 时执行
}else{
    
    
  //条件为 false 时执行
}

//if...else if...else语句
if (){
    
    
 //条件1为 true 时执行
}else if(){
    
    
 //条件2为 true 时执行
}else{
    
    
 //条件都不满足时执行
}
var x = 3;
if(x===2){
    
    
  console.log('x为2')
}else{
    
    
  console.log('x不为2')
}

Insert image description here

var x = 3;
if(x===2){
    
    
  console.log('x为2')
}else if(x===3){
    
    
  console.log('x为3')
}else{
    
    
  console.log('x不为2或3')
}

Insert image description here

(3) Ternary expression

  • grammar
条件 ? 表达式1 : 表达式2
条件为true时,执⾏表达式1,否则执⾏表达式2
var x = 4;
x===3?console.log('x is 3'):console.log('x is not 3')

Insert image description here

4.switch statement in js

A switch statement evaluates an expression and executes the corresponding block of code that matches the result of the expression.

switch(变量/表达式) {
    
    
    case1:  
        // case 1的代码块
        break;

    case2:  
        // case 2的代码块
        break;

    caseN:
        // case N的代码块
        break;

    default:
        // default的代码块
}
var musicType = '摇滚';
switch (musicType) {
    
    
  case '国风':
    console.log('开始播放国风目录音乐');
    break;
  case '舞曲':
    console.log('开始播放舞曲目录音乐');
    break;
  case '摇滚':
    console.log('开始播放摇滚目录音乐');
    break;
  default:
    console.log('未找到对应类型的音乐');
    break;
}

Insert image description here

5. Detailed explanation of loops in js

(1) for loop

The for loop is a loop statement in programming language. The loop statement consists of two parts: the loop body and the loop's judgment condition. Its expression is:

for(单次表达式;条件表达式;末尾循环体){
    
    
  中间循环体;
}
//计算1-9累加
var num = 0;
for(var i = 1;i<10;i++){
    
    
  num+=i;
}
console.log('num='+num)

Insert image description here

(2) while loop

The while loop will execute the code block cyclically only when the condition is true, and the do-while loop means that the code block will be executed regardless of whether the condition is true or not.

while (条件表达式或者变量) {
    
    
 代码块
}

do {
    
    
 代码块
} while (条件);
var a=0
while (a<10) {
    
    
 a++;
}
console.log('a='+a);

Insert image description here

do {
    
    
	console.log('执行代码块');
}while (false) 

Insert image description here

6. Functions in JavaScript

1. Introduction to functions in js

(1) Grammar

function name(参数 1, 参数 2, 参数 3) {
    
    
 //要执⾏的代码
}
function name(参数 1, 参数 2, 参数 3) {
    
    
 //要执⾏的代码
  return x;
}

Some functions can have a return value, and some can not. We will talk about the role of return in detail later.

(2) What are formal parameters?

  • Parameters defined when declaring the function
// a、b是形参
function sum(a,b){
    
      
  // 要执行的代码
  return a+b;
}

(3) What are actual parameters?

  • A parameter passed when calling a function
var num = sum(1,2)  // 1、2就是实参

Feature summary:

  • Formal parameters and actual parameters are one-to-one correspondence

  • The quantity may not correspond

  • The type of the parameter is undefined

  • Functions can set default parameters

  • Actual parameters can be literals or variables

2. Method of js function declaration

(1) Function declaration

function sum(参数) {
    
    
 // 执⾏语句
}

// 匿名函数表达式
var sum=function(参数){
    
    
  // 执⾏语句
}

// 构造函数声明
var sum =new Function([arg1[, arg2[, ...argN]],] functionBody)
function sum1(a,b) {
    
    
 return a+b;
}

var sum2 = function (a,b) {
    
    
 return a+b;
}

var sum3 =new Function('a','b','return a+b;');

console.log(sum1(1,2));
console.log(sum2(1,2));
console.log(sum3(1,2));

Insert image description here

3.js function return knowledge points

(1) As return value

function sum(a,b) {
    
    
 return a+b;
}
var num = sum(1,2);
console.log(num);

It has been verified above.

(2) Interrupt function

function sum(a,b) {
    
    
  console.log('sum='+a+b)
 return;
 console.log('end')
}
sum(1,3);

Insert image description here

4.Js function variable scope

(1) Global variables

  • The global scope runs throughout the entire JavaScript document. All variables except those declared within functions and declared with let and const within curly braces are in the global scope, so they are also called global variables.
  • Once a global variable is declared, it can be used anywhere in the JavaScript document, including inside functions.

(2) Local variables

  • When we define a variable in a function, it can be used anywhere in the function. This is the function scope.
  • However, it should be noted that variables defined within the function cannot be accessed outside the function, so variables defined within the function are also called local variables.

Insert image description here

5. Array-like object arguments in js
  • arguments, which is an object built into the function in js, and the actual parameters of the function method are stored in arguments.
  • To get these actual parameters, you need to use subscripts/indexes to locate each value like an array, but you cannot say it is an array because there are other attributes in it, such as callee.
  • And you cannot use shift, push, join and other methods on it. Named parameters without passed values ​​will automatically be assigned undefined.
function sum(){
    
    
  var result = 0;
  for(var i = 0;i<arguments.length;i++){
    
    
    result+=arguments[i];
  }
  return result;
}
var num = sum(1,2,3,4,5,6);
console.log(num);

Insert image description here

6. Immediate execution of functions in js
  • Immediately execute a function, as the name suggests, declaring a function and calling it immediately is called an immediate execution function.
  • It can also be said that the immediate execution function is a syntax that allows your function to be executed immediately after being defined. The immediate execution function is also called a self-executing function.
  • Immediately executing a function can access global variables internally. But it is inaccessible from outside except within itself.
  • grammar
( function ( “ 参数 ” ) {
    
     " 函数方法 " ; } ) ( “ 给参数传的值 ” )
//我们的函数并没有调用的地方
(function() {
    
    
  console.log('js⽴即执⾏函数');
})();

Insert image description here

7. Understanding closures in js

A closure is a function that can read the internal variables of other functions. For example, in JavaScript, only subfunctions inside a function can read local variables, so closures can be understood as "functions defined inside a function." In essence, closures are a bridge between the inside of a function and the outside of the function.

function sum () {
    
    
  var x = 1;
  return function () {
    
    
    x++;
    console.log(x);
  }
}
var num = sum();
num();
num();

The above code returns a function inside sum and performs ++ on its internal x variable.

Insert image description here

7.JavaScript prototype and prototype chain

1.What is js prototype
  • All functions have a public and non-enumerable property like "prototype" by default, which points to another object, which is the prototype.
  • Whenever an object (function is also an object) is defined, a __proto__ attribute is generated, which is called an implicit prototype.
  • The __proto__ attribute points to the prototype of the object's constructor, which is called an explicit prototype. Every object "inherits" properties from the prototype.
function Person(name){
    
    
  this.name = name;
  this.eat = function (){
    
    
    console.log(this.name+'吃东西');
  }
}
var p = new Person('李祥');
console.log(p);

Insert image description here

Publicity of attribute methods. For example, if I want to add an attribute through prototype, all instantiated objects can access it.

Person.prototype.age=18;
Person.prototype.eat = function (name){
    
    
    console.log(name+'吃东西');
  }
function Person(name){
    
    
  this.name = name;
}
var p1 = new Person('李祥');
var p2 = new Person('张三');
console.log(p1.age);
p1.eat("李祥");
console.log(p2.age);
p2.eat("张三");

Insert image description here

Note: Only the constructor can change the properties on the prototype.

2.What is js prototype chain

Only functions have prototypeproperties, objects have __proto__ || [[prototype]]properties

prototype chain

  • Everything in js is an object, so always accessing __proto__properties will create a chain.
  • The end of the chain is null
  • When the js engine looks for the properties of an object, it will first determine whether the property exists in the object itself.
  • Properties that do not exist will be searched up along the prototype chain.

Insert image description here

function Car() {
    
    }
var car = new Car()

What is prototype chain

原型链解决的主要是继承问题。
每个对象拥有一个原型对象,通过 proto 指针指向其原型对象,并从中继承方法和属性,同时原型对象也可能拥有原型,这样一层一层,最终指向 null(Object.proptotype.__proto__指向的是null)。这种关系被称为原型链(prototype chain),通过原型链一个对象可以拥有定义在其他对象中的属性和方法
3. Type detection in js

(1) typeof: used to determine the type of basic data. It cannot distinguish between objects and arrays.

var a = 1;
console.log('a:'+typeof a);
var b = "1";
console.log('b:'+typeof b); 
var s;
console.log('s:'+typeof s); 
function fun() {
    
    }
console.log('fun:'+typeof fun);
var c = [1, 2, 3];
console.log('c:'+typeof c); 
var o = {
    
     name: "lixiang" };
console.log('o:'+typeof d);

Insert image description here

(2) instanceof: used to determine the type of complex data and can distinguish objects from arrays

instanceofThe operator is used to detect prototypewhether the constructor's properties appear on the prototype chain of an instance object, which can be understood as whether it is an instance of an object.

var arr = [];
console.log(arr instanceof Array); 

var obj = {
    
    };
console.log(obj instanceof Array); 
console.log(obj instanceof Object); 

var fun = new Fun();
console.log(fun instanceof Fun); 

Insert image description here

8. JavaScript partial refresh ajax

1. Understand what JSON data is

(1) What is JSON

  • JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript and is easy to write and read by humans and easy to parse by machines.
  • JSON uses a completely language-independent text format, but also uses conventions similar to those of the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.).
  • These characteristics make JSON an ideal data exchange language.
  • JSON is used to transmit data between networks

(2) JSON syntax format

  • Property name must be a string enclosed in double quotes
  • There cannot be a comma after the last attribute

Insert image description here

(3) Serialization and deserialization

var obj = {
    
    
  name: "李祥",
  age: "18",
};
var a = JSON.stringify(obj); // 序列化、转换成JSON格式
var b = JSON.parse(a); // 反序列化 、转换成对象格式
console.log(a);
console.log(b);

Insert image description here

2. Introduction to ajax and its usage scenarios

(1) What is ajax

The full name of Ajax is "Asynchronous Javascript And XML", which means "Asynchronous JavaScript and XML" in Chinese. It is a technology used to create fast dynamic web pages. It is a technology that can update part of the web page without reloading the entire web page. .

(2) Principle

  • Send an asynchronous request to the server through the XmlHttpRequest object to obtain data from the server

  • Then use js to operate the DOM and update the page

  • It was first introduced in IE5 and is a technology that supports asynchronous requests.

  • To put it simply, javascript can make requests to the server and process responses in a timely manner without blocking the running of the program, achieving the effect of no refresh.

  • Note: JavaScript is single-threaded and will block code execution, so XmlHttpRequest is introduced to process asynchronous data.

3. Handwritten ajax case practice

(1) Ajax creation steps

  • Create ajax object
var xhr;
if (window.XMLHttpRequest){
    
    
  xhr = new XMLHttpRequest();
} else {
    
    // code for IE6, IE5 兼容
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
  • Set request address and method
//第⼀个参数是⽤于指定请求的⽅式,⼀般⽤⼤写
//第二个参数代表请求的URL
//第三个参数是表示是否异步发送请求的布尔值,如果不填写,默认为true,表示异步发送,同步已经被弃用
xhr.open("GET","服务端接口url")
  • Send request (optional parameters, null)
xhr.send()
  • (Register event) Wait until the browser returns the result to accept the response
//注册事件。 onreadystatechange事件,状态改变时就会调用。
//如果要在数据完整请求回来的时候才调用,我们需要手动写一些判断的逻辑。
xhr.onreadystatechange = function () {
    
    
  // 为了保证数据完整返回,我们一般会判断两个值
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
    alert(xhr.responseText);
  } else {
    
    
    alert('出错了,Err:' + xhr.status);
  }
};

(2) Case practice

A test server interface is written here.

Insert image description here

var xhr;
if (window.XMLHttpRequest){
    
    
  xhr = new XMLHttpRequest();
} else {
    
    // code for IE6, IE5 兼容
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET","http://localhost:8088/spring-test/query")
xhr.send();
xhr.onreadystatechange = function () {
    
    
  // 为了保证数据完整返回,我们一般会判断两个值
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
    alert(xhr.responseText);
  } else {
    
    
    alert('出错了,Err:' + xhr.status);
  }
};

Insert image description here

Insert image description here

9.JavaScript Document Object DOM

1. Detailed explanation of DOM in js

(1) DOM (a standard proposed by w3c)

  • DOM is the Document Object Model, which is an abstract concept.
  • Defines methods for accessing and manipulating HTML documents

(2) The difference between HTML and txt text

  • HTML is hypertext, which can contain various formats, functions, links, images, videos, etc.
  • TXT is the extension of a text file, which indicates that this type of file needs to be opened with Notepad for viewing or editing.

(3) What is DOM tree

  • The browser stores structured documents in the browser memory in a "tree" structure.
  • Each HTML element is defined as a node.
  • This node has its own attributes (name, type, content, etc.).
  • Has its own hierarchical relationship (parent, child, sibling).

Insert image description here

2. Common operations of DOM nodes

(1) Find nodes

Method describe
document.getElementById(id) Find elements by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
document.querySelector(selector) Select elements through css selector or ID, pseudo-class cannot be selected
    <h1 id="h1" class="h1">李祥</h1>
    <script>
      //根据标签名
      var h1 = document.getElementsByTagName("h1")[0];
      console.log(h1.outerHTML);
      //根据id
      var h2 = document.getElementById("h1");
      console.log(h2.outerHTML);
      //根据className
      var h3 = document.getElementsByClassName("h1")[0];
      console.log(h3.outerHTML);
      //根据className
      var h4 = document.querySelector(".h1");
      console.log(h4.outerHTML);
      //根据ID
      var h5 = document.querySelector("#h1");
      console.log(h5.outerHTML);
    </script>

Insert image description here

(2) Change element content

Method describe
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change attribute values ​​of HTML elements
element.setAttribute(attribute, value) Change attribute values ​​of HTML elements
element.style.property = new style How to change the style of HTML elements
<h1 id="h1" class="h1">李祥</h1>
<script>
  //根据标签名
  var h1 = document.getElementsByTagName("h1")[0];
  h1.innerHTML = 'lixiang';
  h1.id='h2'
  h1.style.backgroundColor='red'
</script>

Insert image description here

Note: outerHTML will cause styles to be lost.

h1.outerHTML = 'lixiang';

Insert image description here

(3) Add and delete elements

Method describe
document.createElement(element) Create HTML elements
document.removeChild(element) Delete HTML elements
document.appendChild(element) Add HTML elements
document.replaceChild(element) Replace HTML elements
document.write(text) Writable HTML method
var div = document.createElement('div');
div.innerHTML = '我是动态创建的HTML';
document.body.append(div);

Insert image description here

3.JS event operations on DOM

(1) What is an event?

  • Events refer to things that happen on html elements.
  • For example, when a picture element is clicked, a series of operations are triggered.
  • When the event is triggered, you can set a piece of js code to be executed.

(2) Common HTML events

describe event
html element changes onchange
The user clicked on the element onclick
The mouse moves over the element onmouseover
Mouse leaves element onmouseout
press keyboard onkeydown
The page has finished loading onload
<div id="d1" onclick="test()">点击</div>
<script>
 function test(){
    
    
   console.log("点击事件");
 }
</script>

Insert image description here

<div id="d1">点击</div>
<script>
  document.getElementById("d1").addEventListener('click',function(){
    
    
    console.log("点击事件");
  })
</script>

Note: Using addEventListener, you can add several more events.

<div id="d1">点击</div>
<script>
  document.getElementById("d1").addEventListener('click',function(){
    
    
    console.log("点击事件1");
  })
	document.getElementById("d1").addEventListener('click',function(){
    
    
    console.log("点击事件2");
  })
	document.getElementById("d1").addEventListener('click',function(){
    
    
    console.log("点击事件3");
  })
</script>

Insert image description here

<div id="d1">鼠标移入移出事件</div>
<script>
  document.getElementById("d1").addEventListener('mouseover',function(){
    
    
    console.log("鼠标移入事件");
  })
  document.getElementById("d1").addEventListener('mouseout',function(){
    
    
    console.log("鼠标移出事件");
  })
</script>

Insert image description here

4. Some mechanisms of events in js

(1) Two mechanisms of event propagation

Event bubbling: Events are initially received by the most specific element and then propagate upward to less specific nodes. Only listeners marked as non-capturing will be called during the event bubbling phase. That is, those listeners registered when the third parameter is false when calling addEventListener(). The default value is false.

Event capture: Less specific DOM nodes should receive events earlier, while the most specific nodes should receive events last. During this phase, only those listeners set up to work during the capture phase are called. To set a listener for the capture phase, set the third parameter to true when calling addEventListener.

(2) Illustration of event capture and event bubbling

Insert image description here

(3) What is an event agent?

  • Event proxy uses event bubbling to manage all events of a certain type by specifying only one event handler.

(4) Cancel bubbling or capturing

  • Click on the subcategory to display the subcategory, click on the parent category to display the parent category.
<ul id="father">
  父类
<li id="son">子类</li>
</ul>
<script>
document.getElementById("father").addEventListener("click", function (e) {
    
    
  console.log("父类");
});
document.getElementById("son").addEventListener("click", function (e) {
    
    
  console.log("子类");
  e.stopPropagation();
});

Insert image description here

5.Timer in js

(1) Delayed execution

setTimeout(function(){
    
    }, 毫秒)

clearTimeout(timer) // 停止,参数必须是由 setTimeout() 返回的timer
console.log('1');
console.log('2');
setTimeout(function(){
    
    
   console.log('5');
},5000)
console.log('3');
console.log('4');

Insert image description here

(2) Scheduled execution

setInterval(function(){
    
    }, 毫秒)

clearInterval(timer) // 参数必须是由 setInterval() 返回的timer
console.log('1');
console.log('2');
setInterval(function(){
    
    
   console.log('5');
},2000)
console.log('3');
console.log('4');

Insert image description here

10.JavaScript Browser Object BOM

1. Commonly used built-in functions of BOM

(1) What is BOM

BOM (Browser Object Model) is the browser object model. It provides objects that interact with the browser window independently of the content. Its core object is window.

(2) Commonly used BOM objects

  • window object
    • The window object is the top-level BOM object.
    • The window object is an interface for JS to access the browser window.
    • The window object is a global object, and all declared global variables and global methods and functions are ultimately properties or methods of the window object.
    • window.open(): Open a new browser window, accepting four parameters (URL/opening method/window parameters/Boolean value of whether to replace the current page history).
    • window.close() :关闭新打开的窗口(仅限open()打开的窗口)。
    • window.moveTo():移动当前窗口。
    • window.resizeTo():调整当前窗口的尺寸。
  • screen对象 :包含显示设备的信息
    • screen.height、screen.width:返回设备的分辨率。
    • screen.availWidth、screen.availHeight:返回屏幕可用宽高,值为屏幕的实际大小减去操作系统某些功能占据的空间,如系统任务栏。
  • location对象:保存当前文档信息,将URL解析为独立片段
    • location.href 返回当前页面完整的URL ,修改这个属性,即跳转新页面
    • location.hash 返回URL中的hash(#号后跟零或多个字符)
    • location.host 返回服务器名称和端口号
    • location.port 返回服务器端口号
    • location.pathname 返回URL中的目录和文件名
    • location.hostname 返回不带端口号的服务器名称
    • location.protocol 返回页面使用的协议(http://或https://)
    • location.search 返回URL的查询字符串,字符串以问号开头
  • navigator对象:提供一系列属性用于检测浏览器
    • window.navigator.userAgent:通过userAgent可以判断用户浏览器的类型
    • window.navigator.platform:通过platform可以判断浏览器所在的系统平台类型
    • window.navigator.online:判断是否联网
  • history 对象
    • history.back():与在浏览器点击后退按钮相同
    • history.forward():与在浏览器中点击按钮向前相同
    • history.go(参数):前进后退功能,参数如果是1前进一个页面,如果是-1后退一个页面,如果是N则前进或后退N个页面
    • history.length(): 保存历史记录的数量
  • localStorage
    • localStorage.setItem: set value
    • localStorage.removeItem: remove value
2.JavaScript pop-up box

(1) Warning box

alert('hello')

Insert image description here

(2) Confirmation box

var isConfirm = confirm('请确认')
console.log('下⼀步', isConfirm)

Insert image description here

Insert image description here

(3) Prompt box

var isPrompt = prompt('请输⼊姓名')
console.log(isPrompt) // 是null 或者 ⽤户输⼊的值

Insert image description here
Insert image description here

3. Basic concepts of browser cookies

(1) What is Cookie

  • Cookies are used to store browser data on your computer, with a capacity of approximately 4KB.
  • Basic syntax: document.cookie

(2) Cookie function

  • After the browser is closed, the server will forget everything about the user
  • Let the browser remember user information: login information

(3) Cookie operation

  • How to create and read cookies
// 通过Document对象
document.cookie="username=Nick; expires=Thu, 18 Dec 2043 12:00:00 GMT";
  • Delete cookies
// 设置过期时间
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";  //  nul
  • Case
window.onload = function(){
    
    
  checkCookie();
}
// 保存cookie
function setCookie(cname, cvalue, exdays) {
    
    
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = 'expires=' + d.toGMTString();
  document.cookie = cname + '=' + cvalue + ';' + expires;
}

// 获取cookie
function getCookie(cname) {
    
    
  var name = cname + '=';
  var ca = document.cookie.split(';'); // 将多个cookie字符串以;分割数组;
  for (var i = 0; i < ca.length; i++) {
    
    
    if (ca[i].indexOf(name)>= 0) {
    
    
      return ca[i].split('=')[1]
    }
  }
  return '';
}

function checkCookie(){
    
    
  var user=getCookie("username");
  if (user){
    
    
    alert("欢迎 " + user + " 再次访问");
  }
  else {
    
    
    user = prompt("请输入你的名字:","");
      if (user){
    
    
        setCookie("username",user,30);
      }
  }
}

Insert image description hereInsert image description here

Guess you like

Origin blog.csdn.net/weixin_47533244/article/details/133204595
Recommended