JavaScript (1)--A preliminary understanding of JavaScript in this article

01 Preface

Welcome to JavaScriptthe basics of learning tutorial! In the previous tutorials, we have learned about HTMLand CSS, which are the basic languages ​​for building web pages. However, just using HTML and CSS is not enough to achieve interactivity and dynamic effects. For this, we need to learn JavaScript, which is a scripting language used to create dynamic web pages and interactive applications.

JavaScript was created by Brendan Eich in 1995 and was originally designed to implement some simple interactive functions on web pages. Today, JavaScript has become an integral part of web development, it can be used to create dynamic effects, form validation, web games, web applications, and more. At the same time, JavaScript can also run on the backend, using Node.jsthe technology to write server-side applications.

In this tutorial, we'll cover the basics of JavaScript, including syntax, data types, flow control, functions, objects, and more. We'll also learn how to use JavaScript to manipulate HTML elements, handle events, do web programming, and more. This tutorial is designed to enable you to master the basics of JavaScript, and will continue to update the teaching, including the use of JavaScript to implement various Web applications.

01 Overview of JavaScript

1.1 js background

JavaScript is a scripting language widely used in web development and is currently one of the most widely used programming languages ​​in the world. Originally developed by Brendan Eich of Netscape Corporation, JavaScript first appeared in 1995 in the Netscape Navigator 2.0 browser. At that time, JavaScript was designed as a scripting language for web page interaction, mainly used to realize simple interaction and dynamic effects on web pages.

With the development of Web technology and the expansion of application scenarios, the functions of JavaScript have gradually become more powerful and complex, and it has also become an indispensable part of Web development. Today, JavaScript is widely used in web development, mobile application development, desktop applications, game development, server-side programming, and many other fields.

JavaScript is an interpreted language that runs directly in the browser without compilation. It supports multiple programming paradigms such as object-oriented programming, functional programming, and event-driven programming. It has rich built-in functions and third-party libraries, and can quickly realize various functions.

In the past few years, the JavaScript ecosystem has been greatly developed, and the JavaScript language standard has also been updated. The release of ES6, ES7, ES8, ES9, ES10 and other versions has made the JavaScript language features more complete and modern. At the same time, the development of JavaScript frameworks and libraries is also very rapid, such as React, Vue.js, Angular, jQuery etc. These frameworks and libraries have greatly improved the development efficiency and code quality of JavaScript.

Overall, JavaScript is a very important programming language, and learning JavaScript is essential if you want to become a web developer.

1.2 Features of js

Key features of JavaScript include:

  • Interpretation and execution : JavaScript is an interpreted language that can be executed directly without compilation.

  • Scripting language : JavaScript is usually used forwrite script, can embed codes in web pages, combined with HTML and CSS, to make web pages more dynamic and interactive.

  • Object-based : JavaScript is an object-based language. Objects are one of the basic data types of JavaScript and can be used to represent data and behavior.

  • Weakly typed : JavaScript is a weakly typed language, and the type of variables can be automatically converted according to the context.

  • Event-driven : JavaScript supports event-driven programming, which canRespond to user actions by listening to events

  • Cross-platform: JavaScript can run in different operating systems and browsers to achieve cross-platform applications.

  • Openness: JavaScript is an open language with a huge developer community and rich third-party libraries and frameworks, which can be easily extended and customized.

02 JavaScript syntax

2.1 Citation

JavaScript can be used in two ways: tag reference and file reference.

  • Tag reference<script> refers to using tags to embed JavaScript code in HTML files , for example:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>标签引用示例</title>
  </head>
  <body>
    <h1>JavaScript标签引用示例</h1>
    <script>
      // 在这里编写JavaScript代码
    </script>
  </body>
</html>
  • File references<script> refer to external JavaScript files using tags in HTML files , for example:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>文件引用示例</title>
    <script src="path/to/javascript.js"></script>
  </head>
  <body>
    <h1>JavaScript文件引用示例</h1>
  </body>
</html>

2.2 JavaScript output

  1. Outputted information can be added to an HTML page using DOM manipulation, for example by innerHTMLmodifying the content of an element. For example:
    <script>
      document.getElementById("output").innerHTML = "Hello, world!";
    </script>
  1. Console output: In the browser's developer tools, you can use console.log()methods to output information to the console. For example:
  console.log("Hello, world!");
  1. Popup window output: You can use alert()the method to pop up a window with a message. For example:
alert("Hello, world!");

2.3 JavaScript comments

JavaScript has two annotation methods:

  • Single-line comments: start with a double slash (//), followed by the content of the comment.
  • Multi-line comments: start with a slash and an asterisk (/*), end with an asterisk and a slash (*/), and comment content in between.

Comments can be used for explaining code, marking code, debugging, etc., and are very helpful for developing and maintaining code. Comments are not executed by the JavaScript engine and are only read by the programmer.

2.4 Variable declaration

In JavaScript, there are three ways of declaring variables:

  1. Use to var declare variables, which can be used to declare global variables or variables within function scope.

var a = 10; // 声明一个全局变量a,值为10
function foo() {
    
    
  var b = 20; // 声明一个函数作用域内的变量b,值为20
}
  1. Use to letdeclare variables, which are used to declare variables in block-level scope, such as variables in for loops.
function foo() {
    
    
  let a = 10; // 声明一个块级作用域内的变量a,值为10
  if (true) {
    
    
    let b = 20; // 声明一个块级作用域内的变量b,值为20
  }
  console.log(a); // 输出 10
  console.log(b); // 报错,b未定义
}
  1. Use to const declare a constant, which is used to declare a variable whose value does not change, and cannot be assigned again after the declaration.
const PI = 3.1415926; // 声明一个常量 PI,值为 3.1415926
PI = 3.14; // 报错,常量不可再次赋值

  It should be noted that the variables and constants declared with let and const are only valid in the current block-level scope, while the scope of variables declared with var is within the current function or the global scope. In addition, variables declared by let and const do not have variable promotion and must be declared first before use, while variables declared by var have variable promotion.

2.5 Data Types

JavaScript has seven built-in data types:

  • Number: Integer and floating point numbers, such as 42 or 3.14.
  • BigInt (large integer): used to represent a larger range of integers, such as 9007199254740992n.
  • String (string): A string of characters, such as "hello world".
  • Boolean: true or false.
  • Null (empty value): Indicates that there is no value, only one value is null.
  • Undefined (undefined): Indicates that a variable has been declared but not assigned a value.
  • Object: A complex data type used to store various data and functions. Objects can contain key-value pairs, as well as methods and properties.

Specifically expand the following two:

  1. UndefinedTypes have only one value, the special undefined.

When a variable is declared with var but not initialized, the value of the variable is undefined.

Note: Using typeof for uninitialized and undeclared variables will return "undefined".

  1. Null
    The Null type is the second data type that has only one value, and this particular value is null.
    The undefined value is actually derived from the null value, so if you compare undefined and null for equality, it will return true.

Note: From a semantic point of view, null means an empty object, so using typeof to check for null will return an Object.

2.6 Mandatory type conversion

2.6.1 Convert to String type

There are three ways to convert other values ​​into strings: toString(), String(), and string.

Method 1: Call the method of the converted data type toString(). This method will not affect the original variable, and it will return the converted result.

Note: The two values ​​of null and undefined do not have toString() methods. If their methods are called, an error will be reported.

var a = 123;
a = a.toString();
console.log(a);
console.log(typeof a);

Method 2: Call String()the function and pass the converted data to the function as a parameter. When using the String() function to perform mandatory type conversion, the toString() method is actually called for Number and Boolean, butFor null and undefined, the toString() method will not be called, it will directly convert null to "null" and undefined to "undefined".

var a = 123;
a = String(a);
console.log(a);
console.log(typeof a);

var b = undefined;
b = String(b);
console.log(b);
console.log(typeof b);

var c = null;
c = String(c);
console.log(c);
console.log(typeof c);

Method 3: For any data type+""

var a = 123;
a = a + "";
console.log(a);
console.log(typeof a);

2.6.2 Convert to Number type

There are three functions that convert non-numeric values ​​to numeric values: Number(), , parseInt()and parseFloat(). Number() can be used toConvert any typedata, while the latter two can only be used forconvert string. parseInt() will only convert a string to an integer, while parseFloat() can convert a string to a float.

Detailed Explanation: Using Number()Functions

string --> number

  • If it is a string of pure numbers, convert it directly to a number
  • Convert to NaN if there are non-numeric contents in the string
  • Converts to 0 if the string is an empty string or a string full of spaces

boolean --> number

  • true turns into 1
  • false turns to 0

null --> number

  • null turns into 0

undefined --> number

  • undefined is converted to NaN

Note: If you use parseInt() or parseFloat() on a non-String, it will first convert it to a String and then operate on it.

2.6.3 Conversion to Boolean type

To convert other data types to Boolean, only Boolean()functions can be used.

Use the Boolean() function:

  • Number —> Boolean
    True except for 0 and NaN
  • String —> Boolean
    True except for the empty string
  • Both null and undefined are converted to false
  • Object also converts to true

2.7 Operators

Operators in JavaScript can be divided into the following categories:

  • Arithmetic operators: Used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulo, etc. Common arithmetic operators include +, -, *, /, %, etc.
  • Assignment operator: used to assign values ​​to variables, for example, to assign 5 to variable x, you can use x = 5. Common assignment operators include =, +=, -=, *=, /=, %=, etc.
  • Comparison operator: used to compare the magnitude relationship between two values ​​and return a Boolean value true or false. Common comparison operators include ==, !=, ===, !==, >, <, >=, <=, etc.
  • Logical operators: Used to combine multiple conditions and return a boolean value true or false. Common logical operators include && (logical AND), || (logical OR), and ! (logical NOT).
  • Bitwise operators: used to operate on binary numbers. Common bitwise operators include & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise inversion), << (left shift), >> (signed right shift ) and >>> (unsigned right shift).
  • Conditional operator: Also known as ternary operator, it is used to perform different operations based on a condition. It consists of a question mark and a colon in the form condition ? expr1 : expr2.
  • Other operators: including typeof operator, instanceof operator, delete operator, etc.

2.7.1 Logical operators

We can talk about logical operators in detail:

&& And: && can perform an AND operation on the values ​​on both sides of the symbol and return the result. The operation rules are as follows:

  • As long as one of the two values ​​​​is false, it returns false, and only when both values ​​​​are true, it returns true
  • The "and" in JS is a short-circuit and, if the first value is false, the second value will not be checked
  • When non-Boolean value: if both are true, return the second value, if both values ​​are false, return the value of the first false

|| Or: || can perform an OR operation on the values ​​on both sides of the symbol and return the result. The operation rules are as follows:

  • As long as one of the two values ​​is true, true will be returned, and false will only be returned if both values ​​are false
  • The "or" in JS is a short-circuit or, if the first value is true, the second value will not be checked
  • When non-boolean value: if both are false, return the second value, if there is true in the two values, return the value of the first true

! Not: ! can be used to perform a non-operation on a value. The so-called non-operation is to invert a Boolean value. True becomes false, and false becomes true. The operation rules are as follows:

  • If a value is negated twice, it does not change
  • When it is not a boolean value: it will be converted to a boolean value first, and then negated, so we can use this feature to convert another data type into a boolean value, and can invert twice for an arbitrary data type to Convert it to a Boolean value, the principle is the same as the Boolean() function

2.7.2 Operator precedence

For details, please refer to this article: http://c.biancheng.net/view/161.html , no redundant explanation here.

2.8 Code blocks

A code block is a statement written in curly braces {}, so that a collection of multiple statements can be used as a single statement. For example:

{
    
    
    var a = 123;
    a++;
    alert(a);
}

We generally use code blocks to group statements that need to be executed together. It should be noted that there is no need to add a semicolon at the end of the code block.

03 Object Basics

ObjectA type, which we also refer to as an object, is a reference data type in JavaScript. It is a composite value that aggregates many values ​​together and can be accessed by name. An object can also be thought of as an unordered collection of properties, each of which is a key/value pair. In addition to creating its own properties, objects can also 原型inherit properties from an object named .

Note: With the exception of strings, numbers, true, false, null, and undefined, values ​​in JavaScript are objects.

3.1 Creating objects

In JavaScript, there are several ways to create objects, including:

  • Object literals
    are an easy way to create objects directly using object literals, as follows:
const obj = {
    
    
  key1: value1,
  key2: value2,
  // ...
};
  • Constructors Constructors
    are used to create objects, which are aMore commonly usedThe way. First, you need to define a constructor, and then newcall the constructor to create an object through keywords, as follows:
function Person(name, age) {
    
    
  this.name = name;
  this.age = age;
}

const person1 = new Person('Alice', 18);
const person2 = new Person('Bob', 20);
  • Object.create()
    Use the Object.create() method to create an object by specifying a prototype, as follows:
const protoObj = {
    
     x: 1 };
const obj = Object.create(protoObj);
  • Classes
    The class keyword was introduced in ES6 and can be used to create classes. A class is essentially a special kind of constructor, as follows:
class Person {
    
    
  constructor(name, age) {
    
    
    this.name = name;
    this.age = age;
  }
}

const person1 = new Person('Alice', 18);
const person2 = new Person('Bob', 20);

These are common ways to create objects in JavaScript. Choosing the right way according to different needs and scenarios can improve the readability and maintainability of the code.

3.2 How to use

Add, deletedelete, modify and check, just like other languages. Mainly talking about traversal:
case demonstration:

var person = {
    
    
    name: "zzc",
    age: 18
}

for (var personKey in person) {
    
    
    var personVal = person[personKey];
    console.log(personKey + ":" + personVal);
}

3.3 Object type combing

3.3.1 Basic data types

Variables in JavaScript may contain values ​​of two different data types: primitive data types and reference data types.

Values ​​of primitive data types cannot be modified and are immutable. The comparison of basic data types is the comparison of values, that is, as long as the values ​​of two variables are equal, we consider the two variables equal.

Values ​​of reference types are objects held in memory. When a variable is an object, what is actually stored in the variable is not the object itself, but a reference to the object. When copying a value of a reference type from one variable to another, the reference to the object is copied into the variable instead of a new object being created. At this time, the two variables point to the same object. So changing one of the variables affects the other.

Stack and heap combing, JavaScript data is saved to stack memory and heap memory at runtime.

Simply put, stack memory is used forSave variables and primitive types, the heap memory is used forsave object

When we declare a variable, we actually create a space in the stack memory to save the variable. If it is a basic type, it will be saved directly in the stack memory . If it is a reference type, it will be saved in the heap memory. The actual address of the object in the heap memory is actually saved in the variable .

04 function

A JavaScript function is a reusable block of code that accepts parameters, performs calculations, and returns a result. It can be defined as a standalone function or as a method on an object. JavaScript functions can be passed, assigned, and used like other data types, making code more modular and flexible.

The functions in JavaScript and Java have many similarities in definition and use, and the usage method is almost the same as that of JAVA. they allNeed to declare the function name, parameters and return type. But JavaScript functions have the following characteristics:

  • JavaScript functions are first-class objects: JavaScript functions are first-class citizens and can be passed, assigned, and used like other data types.
  • JavaScript functions do not have overloading: Java functions can have different method names and parameter types, but JavaScript functions can only have one name and can accept different numbers and types of parameters.
  • JavaScript functions have default parameters: JavaScript functions can define default parameter values ​​for the convenience of the caller.
  • JavaScript functions have dynamic scope : The scope of JavaScript functions is dynamic, they canaccess variables in the context in which they are defined
  • JavaScript functions can be called in different ways: JavaScript functions can be called as ordinary functions, they can also be called as methods on objects, and even methods can be used call()to apply()change the scope of functions.

In short, although JavaScript functions and Java functions have some similarities, since JavaScript is a dynamic language, the characteristics and usage of its functions have greater flexibility.

4.1 Function Creation

Use function expressions to create a function (commonly used)

Grammar format:

var 函数名  = function([形参1,形参2,...,形参N]) {
    
    
    语句....
}

Sample code:

var fun  = function() {
    
    
    console.log("这是我的第三个函数");
}

4.2 Function parameters

  • When calling a function, the parser does not check the types of the arguments. So pay attention to whether it is possible to receive illegal parameters. If possible, you need to check the type of the parameter. The actual parameter of the function can be any data type.
  • The parser also does not check the number of arguments when calling a function. Redundant actual parameters will not be assigned. If the number of actual parameters is less than the number of formal parameters, the formal parameters without corresponding actual parameters will be undefined

4.3 Nested functions

Nested function: The function declared in the function is a nested function, and the nested function can only be accessed in the current function, and cannot be accessed outside the current function.

Case presentation:

function fu() {
    
    
    function zi() {
    
    
        console.log("我是儿子")
    }

    zi();
}

fu();

4.4 Functions in Objects

The attribute value of an object can be any data type, or it can be a function.

If a function is saved as a property of an object, then we call this function a method of this object, and calling this function means calling a method of an object.

Note: The difference between methods and functions is only in name, there is no other difference

Case presentation:

var person = {
    
    
    name: "zhangsan",
    age: 18,
    sayHello: function () {
    
    
        console.log(name + " hello")
    }
}

person.sayHello();

05 Advanced use of objects

5.1 Use constructors to create objects (most commonly used)

How does the constructor perform the process of creating an object? Let me explain again:

  1. Call the constructor, which immediately creates a new object
  2. Set the newly created object as this in the function, and this can be used in the constructor to refer to the newly created object
  3. Execute the code in a function line by line
  4. Return the newly created object as the return value
// 使用构造函数来创建对象
function Person(name, age) {
    
    
    // 设置对象的属性
    this.name = name;
    this.age = age;
    // 设置对象的方法
    this.sayName = function () {
    
    
        console.log(this.name);
    };
}

var person1 = new Person("孙悟空", 18);
var person2 = new Person("猪八戒", 19);
var person3 = new Person("沙和尚", 20);

console.log(person1);
console.log(person2);
console.log(person3);

There is a new situation in this. In order not to confuse everyone, let me sort it out again:

  • When called as a function, this is window
  • When called as a method, whoever calls the method this is who
  • When called as a constructor, this is the newly created object

We can instanceofcheck whether an object is an instance of a class using the operator, which returns true or false. Case presentation:

console.log(person1 instanceof Person);

5.2 Prototype

Is there a way that I only add a function to the global object of the Person class, and then reference it in the class? The answer is definitely yes, which requires a prototype object.

In JavaScript, every object has a prototype object, which is a reference to other objects. Prototype objects can contain shared properties and methods that can be inherited by objects.

When we access a property or method of an object, if the object itself does not have this property or method, the JavaScript engine will look it up in the prototype object of the object. If there is no prototype object, it will continue to look for the prototype object of the prototype object until Object.prototype.

Prototype is one of the mechanisms for implementing inheritance in JavaScript, properties and methods can be inherited through the prototype chain. Using prototypes can reduce repetitive code and memory usage, and improve program performance.



  You can use constructors and prototypes to create objects and add variables. For example, we can create a constructor called Person and add three variable names to its prototype: name, age, and gender. Case presentation:

function Person(name, age, gender) {
    
    
  this.name = name;
  this.age = age;
  this.gender = gender;
}

Person.prototype.nickname = "";

let person1 = new Person("Alice", 25, "female");
let person2 = new Person("Bob", 30, "male");

person1.nickname = "Ally";

console.log(person1.name); // Output: "Alice"
console.log(person2.age); // Output: 30
console.log(person1.gender); // Output: "female"
console.log(person1.nickname); // Output: "Ally"
console.log(person2.nickname); // Output: ""
  1. So what exactly is a prototype?

For each function we create, the parser will add an attribute to the function prototype, and this attribute corresponds to an object, which is what we call a prototype object, namelyexplicit prototype, the prototype object is equivalent to a public area, all instances of the same class can access this prototype object, and we can uniformly set the common content in the object to the prototype object.

If the function calls the prototype as an ordinary function, it has no effect. When the function is called as a constructor, the object it creates will have an implicit property pointing to the prototype object of the constructor. We can access this property __ proto__(隐式原型)by . When we access a property or method of an object, it will first look for it in the object itself, if it exists, it will be used directly, if not, it will look for it in the prototype object, and if it is found, it will be used directly.

When we create a constructor in the future, we can uniformly add the properties and methods shared by these objects to the prototype object of the constructor, so that we can make each Objects have these properties and methods already.

  1. What is Prototype Chain?

When an object accesses a property or method, JavaScript will first search on the object itself, and if it cannot find it, it will search on the prototype of the object, and then search on the prototype of the prototype until it finds the property or method or Search until the top of the prototype chain. It is mainly used to implement functions similar to inheritance in JAVA.

5.3 Using the prototype chain to realize composition inheritance

Core idea: Combination inheritance of prototype chain + borrowing constructor

Basic method:

  • Use the prototype chain to realize the method inheritance of the parent type object
  • Initialize the same property with super()a borrowed supertype constructor

Disadvantage description:

  • The instance properties and methods in the parent class exist both in the instance of the subclass and in the prototype of the subclass, but only occupy memory. Therefore, when using a subclass to create an instance object, there will be two identical copies in its prototype properties and methods.

Note: This method is the most commonly used inheritance pattern in JavaScript.

Code example:

function Person(name, age) {
    
    
    this.name = name;
    this.age = age;
}

Person.prototype.setName = function (name) {
    
    
    this.name = name;
};

function Student(name, age, price) {
    
    
    Person.call(this, name, age); // 为了得到父类型的实例属性和方法
    this.price = price; // 添加子类型私有的属性
}

Student.prototype = new Person(); // 为了得到父类型的原型属性和方法
Student.prototype.constructor = Student; // 修正constructor属性指向
Student.prototype.setPrice = function (price) {
    
     // 添加子类型私有的方法 
    this.price = price;
};

var s = new Student("孙悟空", 24, 15000);
console.log(s.name, s.age, s.price);
s.setName("猪八戒");
s.setPrice(16000);
console.log(s.name, s.age, s.price);

5.4 Garbage collection mechanism

When an object does not have any variables or attributes to refer to it, we will never be able to operate the object at this time. At this time, this object is a garbage. Too many such objects will occupy a large amount of memory space, causing the program to run slowly , so this garbage must be cleaned up.

There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory. We don't need and can't perform garbage collection operations. All we need to do is set the objects that are no longer used to null.

person1 = null;
person2 = null;
person3 = null;

5.5 Scope (Scope)

In JavaScript, the visible range of a variable is called the scope. Variables declared within a function are only visible inside that function, while variables declared outside a function are globally visible. JavaScript uses lexical scope, that is, the scope of variables is determined when the function is declared. There are two scopes in JS:

  • Global scope: scriptThe JavaScript code written directly in the label is in the global scope. The global scope is created when the page is opened and destroyed when the page is closed.
  • Function scope: The function scope is created when the function is called, and the function scope is destroyed after the function is executed.

5.6 Callback function

A callback function is a function that is passed into another function when the function executes. The callback function is called when the passed function performs a specific operation to achieve more flexible code structure and complex functions. Callback functions can be called when an asynchronous operation completes, or they can be used to handle events.

  • Typically, callback functions in JavaScript are passed to other functions to be executed when an asynchronous operation completes. For example, when the user clicks a button, the browser executes the event handler function in a separate thread and calls the callback function when the event handler function completes.

  • Callback functions can also be used to handle asynchronous requests and other long-running operations. For example, when we request data from a server, we need to wait for the server to respond due to network latency. In this case, we can pass a callback function to the request function to execute the callback function and process the response data after the request is completed.

  • Callback functions can also be used to handle events in JavaScript. For example, when the user clicks a button, the browser calls the specified event handler function and calls the callback function after the event handler function completes.

In general, callback functions are a very common JavaScript programming pattern that provide a way to handle asynchronous operations and events. In the sorting algorithm, the callback function can also be used to specify the sorting rules. For example, if you want to sort an array of strings, you can use the callback function to specify ascending or descending alphabetical order.

5.6.1 Callback function to achieve sorting

Here is an example of sorting using a callback function (in the JavaScript language):

function sortArray(arr, callback) {
    
    
  return arr.sort(callback);
}

const arr = ["apple", "banana", "cherry", "date"];
const ascendingOrder = (a, b) => a.localeCompare(b); // 回调函数用于按字母升序排序
const descendingOrder = (a, b) => b.localeCompare(a); // 回调函数用于按字母降序排序

console.log(sortArray(arr, ascendingOrder)); // ["apple", "banana", "cherry", "date"]
console.log(sortArray(arr, descendingOrder)); // ["date", "cherry", "banana", "apple"]

const is the keyword used to declare constants in JavaScript, and its name comes from the word constant (constant). Variables declared using const cannot be reassigned, which means that once a const declared variable is assigned a value, that value cannot be changed. A variable declared with const must be assigned a value at the time of declaration, and cannot be assigned in the following code. This differs from variables declared with let and var, which can be assigned a value at any time after declaration.

5.6.2 Simple way to implement sorting

var arr = [1, 3, 2, 11, 5, 6];

//如果需要升序排列,则返回 a-b,返回正值,则True实现调换,False实现位置不变
//如果需要降序排列,则返回 b-a
arr.sort(function (a, b) {
    
    
    return a - b;
});
console.log(arr);

06 javascript commonly used objects

6.1 Arrays

in javascript isBacking arrays can be distinct elements, which is related to the weak type of JavaScript. When using typeofinspect an array object will be returned object.

6.1.1 Array creation and basic operations

var arr = [1, "2", 3, "4", 5, "6", 7, "8", 9];

/*增*/
var result = arr.push("唐僧", "蜘蛛精", "白骨精", "玉兔精");

/*删*/
var result = arr.pop();

/* 遍历*/
for (var i = 0; i < arr.length; i++) {
    
    
    console.log(arr[i]);
}

6.1.2 Array extension methods

unshift()Method demonstration: This method adds one or more elements to the beginning of the array and returns the new array length

var result = arr.unshift("牛魔王", "二郎神");

shift()Method demonstration: This method can delete the first element of the array and return the deleted element as the return value

var result = arr.shift();

slice()Method demonstration: This method can be used to extract specified elements from an array. This method does not change the element array, but encapsulates the intercepted elements into a new array and returns

result = arr.slice(0, -2);

Note: The index can pass a negative value. If a negative value is passed, it will be calculated from the back to the front. -1 means the first from the bottom, and -2 means the second to the last.

splice()Method demonstration: This method can be used to delete the specified element in the array. This method will affect the original array, delete the specified element from the original array, and return the deleted element as the return value. Parameters
:

  • The first parameter: the index indicating the starting position
  • The second parameter: indicates the number of elements to delete
  • The third parameter and subsequent parameters: some new elements can be passed, and these elements will be automatically inserted in front of the starting position index
result = arr.splice(1, 0, "牛魔王", "铁扇公主", "红孩儿");

concat()Method demonstration: This method can connect two or more arrays

var arr2 = ["白骨精", "玉兔精", "蜘蛛精"];
var arr3 = ["二郎神", "太上老君", "玉皇大帝"];
var result = arr.concat(arr2, arr3, "牛魔王", "铁扇公主")

join()Method demonstration: This method can convert an array into a string. You can specify a string as a parameter in join(). This string will become the connector of the elements in the array. If you do not specify a connector, it will be used by default. as connector

var arr = ["孙悟空", "猪八戒", "沙和尚"];
var result = arr.join("@-@");
console.log(result);

6.2 Date object

A Date object is used in JavaScript to represent a time. If a Date object is created directly using a constructor, it will be encapsulated as the current code execution time.
The current date can be obtained using the Date object in JavaScript. The specific operation is as follows

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const day = today.getDate();

const dateString = `${
      
      year}-${
      
      month.toString().padStart(2, '0')}-${
      
      day.toString().padStart(2, '0')}`;
console.log(dateString); // 输出类似于 "2022-04-05" 的字符串

6.3 String object

6.3.1 Overview

JS provides us with three wrapper classes, through which the data of basic data types can be converted into objects

  • String(): The basic data type string can be converted to a String object
  • Number(): Can convert numbers of basic data types to Number objects
  • Boolean(): Boolean values ​​of basic data types can be converted to Boolean objects

But note: we will not use objects of basic data types in practical applications. If objects of basic data types are used, some unexpected results may be brought about when doing some comparisons. In this chapter, we focus on introducing Properties and methods of the String() object.

6.3.2 Methods

slice()Method demonstration: the specified content can be intercepted from the string, and the original string will not be affected, but the intercepted content will be returned

parameter:

  • The first parameter: the index of the starting position (including the starting position)
  • The second parameter: the index of the end position (not including the end position), if the second parameter is omitted, all subsequent ones will be intercepted
var str = "Hello,World!";
var result = str.slice(1, 4);

split()Method demonstration: This method can split a string into an array, requires a string as a parameter, and will split the array according to the string

var str = "Hello,World!";
var result = str.split(",");
console.log(result);

07 Extension of JavaScript

  Traditional relational database storage methods require data conversion between the client and server, which requires additional time and resources. And JSON(JavaScript Object Notation) is a lightweight data exchange format, which has the advantages of being concise, easy to read, write and parse, etc. It can effectively reduce the burden of network transmission and improve the efficiency of data transmission.

  JavaScript is a widely used language that can easily parse data in JSON format, so JSON has also become a commonly used data format in browsers. With the development of modern web applications, the application of JSON format has become more and more extensive, and JavaScript has therefore become more important.

The composition of JavaScript mainly consists of the following:
insert image description here

The next article will mainly talk about BOM and DOM, so stay tuned~

Guess you like

Origin blog.csdn.net/qq_54015136/article/details/129857042