JavaScript basics - simple and easy to understand summary

The basics of JavaScript mainly include data types, variables and constants, operators, conditional statements, loop statements, functions, objects and object-oriented programming, arrays, DOM operations, and asynchronous programming.

  1. Data types:
    JavaScript has basic data types and reference data types. Basic data types include Number, String, Boolean, Null, Undefined and Symbol. Reference data types include Object and Array.

  2. Variables and constants:
    Use the var, let or const keywords to declare variables and constants. Var is the ES5 way of declaring variables, and let and const are the new block-level scope declaration methods of variables and constants in ES6.

var x = 5; // 声明一个变量x并赋值为5
let y = 10; // 声明一个块级作用域的变量y并赋值为10
const z = 15; // 声明一个块级作用域的常量z并赋值为15
  1. Operators:
    JavaScript supports various operators, including arithmetic operators (+, -, ,/, %), assignment operators (=, +=, -=, =, /=), comparison operators (=, !=, !==, >, <, >=, <=), logical operators (&&, ||, !), etc.

  2. Conditional statements:
    Use if statements, switch statements, etc. for conditional judgment and branch control.

let num = 5;
if (num > 0) {
    
    
  console.log("Positive");
} else if (num < 0) {
    
    
  console.log("Negative");
} else {
    
    
  console.log("Zero");
}

switch (num) {
    
    
  case 1:
    console.log("One");
    break;
  case 2:
    console.log("Two");
    break;
  default:
    console.log("Other");
    break;
}
  1. Loop statements:
    Use for loops, while loops, do-while loops, etc. for loop control.
for (let i = 0; i < 5; i++) {
    
    
  console.log(i);
}

let j = 0;
while (j < 5) {
    
    
  console.log(j);
  j++;
}

let k = 0;
do {
    
    
  console.log(k);
  k++;
} while (k < 5);
  1. Functions:
    Functions are an important concept in JavaScript that encapsulate reusable blocks of code. You can use the function keyword to define functions, or you can use arrow functions (new in ES6).
function add(a, b) {
    
    
  return a + b;
}

const multiply = (a, b) => a * b;
  1. Objects and Object-Oriented Programming:
    JavaScript is an object-oriented programming language that allows object-oriented programming using objects and classes. Objects are composed of properties and methods, and objects can be created using object literals or constructors.
const person = {
    
    
  name: "John",
  age: 30,
  greet: function() {
    
    
    console.log("Hello, " + this.name);
  }
};

class Rectangle {
    
    
  constructor(width, height) {
    
    
    this.width = width;
    this.height = height;
  }

  getArea() {
    
    
    return this.width * this.height;
  }
}
  1. Array:
    An array in JavaScript is a special object that can store multiple values ​​and provides some commonly used array methods, such as push, pop, shift, unshift, etc.
const numbers = [1, 2, 3, 4, 5];
numbers.push(6); // 在数组末尾添加一个元素
numbers.pop(); // 删除数组末尾的一个元素
numbers.shift(); // 删除数组开头的一个元素
numbers.unshift(0); // 在数组开头添加一个元素
  1. DOM operation:
    JavaScript can realize dynamic operations on web pages by operating the Document Object Model (DOM), including the creation, deletion, modification, event binding, etc. of elements.
const element = document.createElement("div"); // 创建一个div元素
element.textContent = "Hello, World!"; // 设置元素的文本内容
document.body.appendChild(element); // 将元素添加到文档中

const button = document.getElementById("myButton"); // 获取id为myButton的按钮元素
button.addEventListener("click", function() {
    
    
  console.log("Button clicked");
});
  1. Asynchronous programming:
    JavaScript is a single-threaded language, but when processing some time-consuming operations (such as network requests, file reading and writing, etc.), using synchronous methods will cause the program to block. To solve this problem, JavaScript introduced the concept of asynchronous programming.

Common asynchronous programming methods include callback functions, Promise and async/await.

  • Callback functions: You can handle the results of an asynchronous operation by passing a function as a parameter to another function and calling the function at the appropriate time.
function fetchData(callback) {
    
    
  setTimeout(() => {
    
    
    const data = "Hello, World!";
    callback(data); // 异步操作完成后调用回调函数
  }, 1000);
}

function processData(data) {
    
    
  console.log(data);
}

fetchData(processData); // 输出:Hello, World!
  • Promise: Promise is an object used to handle asynchronous operations. It can represent the final completion or failure of an asynchronous operation, and can call multiple asynchronous operations in a chain.
function fetchData() {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      const data = "Hello, World!";
      resolve(data); // 异步操作成功时调用resolve
    }, 1000);
  });
}

fetchData()
  .then(data => {
    
    
    console.log(data); // 输出:Hello, World!
  })
  .catch(error => {
    
    
    console.error(error);
  });
  • async/await: async/await is an asynchronous programming method based on Promise. It uses async functions to define asynchronous operations and uses the await keyword to wait for the completion of a Promise.
function fetchData() {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      const data = "Hello, World!";
      resolve(data); // 异步操作成功时调用resolve
    }, 1000);
  });
}

async function processData() {
    
    
  try {
    
    
    const data = await fetchData();
    console.log(data); // 输出:Hello, World!
  } catch (error) {
    
    
    console.error(error);
  }
}

processData();
  1. Error handling:
    You can use try-catch statements in JavaScript to capture and handle errors. You can write code that may raise an error in a try block and then handle the error in a catch block.
try {
    
    
  // 可能引发错误的代码
} catch (error) {
    
    
  // 处理错误的代码
}
  1. JSON:
    JavaScript Object Notation (JSON) is a commonly used data format used to store and exchange data. You can use JSON.stringify() to convert JavaScript objects to JSON strings and JSON.parse() to convert JSON strings to JavaScript objects.
const person = {
    
    
  name: "John",
  age: 30
};

const jsonStr = JSON.stringify(person); // 将对象转换为JSON字符串
console.log(jsonStr); // 输出:{"name":"John","age":30}

const jsonObj = JSON.parse(jsonStr); // 将JSON字符串转换为对象
console.log(jsonObj); // 输出:{ name: "John", age: 30 }
  1. Modularity:
    Modularity in JavaScript can split code into multiple modules, each module has its own scope, and can share code through import and export.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import {
    
     add, subtract } from "./math.js";

console.log(add(5, 3)); // 输出:8
console.log(subtract(5, 3)); // 输出:2
  1. AJAX:
    Asynchronous JavaScript And XML (AJAX) in JavaScript can send asynchronous requests through the XMLHttpRequest object to interact with the server.
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true); // 发送GET请求
xhr.onreadystatechange = function() {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send();
  1. ES6+ features:
    ES6 and its subsequent versions introduce many new features and syntax sugar, such as arrow functions, template strings, destructuring assignment, default parameters, expansion operators, etc.
const greet = name => `Hello, ${
      
      name}!`; // 箭头函数
console.log(greet("John")); // 输出:Hello, John!

const person = {
    
    
  name: "John",
  age: 30
};

const {
    
     name, age } = person; // 解构赋值
console.log(name); // 输出:John
console.log(age); // 输出:30

function multiply(a, b = 1) {
    
    
  return a * b;
}

console.log(multiply(5)); // 输出:5
console.log(multiply(5, 3)); // 输出:15

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // 展开运算符
console.log(newNumbers); // 输出:[1, 2, 3, 4, 5]

Guess you like

Origin blog.csdn.net/ACCPluzhiqi/article/details/133296383