Skip to Content
Nextra 4.0 is released 🎉
编程语言JavaScript

JavaScript 编程语言学习指南

JavaScript 是一种动态类型、解释型的编程语言,是Web开发的核心技术之一。

目录

基础语法

变量和数据类型

// 变量声明 let name = "张三"; const age = 25; var oldWay = "不推荐使用"; // 基本数据类型 let string = "字符串"; let number = 42; let boolean = true; let nullValue = null; let undefinedValue = undefined; let symbol = Symbol("唯一标识符"); // 引用数据类型 let object = { name: "张三", age: 25 }; let array = [1, 2, 3, 4, 5]; let function = function() { return "函数"; };

控制流

// if-else 语句 if (condition) { console.log("条件为真"); } else if (anotherCondition) { console.log("另一个条件为真"); } else { console.log("所有条件都为假"); } // switch 语句 switch (value) { case 1: console.log("值为1"); break; case 2: console.log("值为2"); break; default: console.log("其他值"); break; } // 循环 for (let i = 0; i < 10; i++) { console.log(i); } // for...of 循环(ES6) for (const item of array) { console.log(item); } // for...in 循环(遍历对象属性) for (const key in object) { console.log(`${key}: ${object[key]}`); } // while 循环 while (condition) { // 循环体 } // do...while 循环 do { // 循环体 } while (condition);

函数

// 函数声明 function greet(name) { return `Hello, ${name}!`; } // 函数表达式 const greet2 = function(name) { return `Hello, ${name}!`; }; // 箭头函数(ES6) const greet3 = (name) => `Hello, ${name}!`; // 默认参数 function greet4(name = "World") { return `Hello, ${name}!`; } // 剩余参数 function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); }

ES6+ 新特性

解构赋值

// 数组解构 const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // 对象解构 const person = { name: "张三", age: 25, city: "北京" }; const { name, age, country = "中国" } = person; console.log(name); // "张三" console.log(country); // "中国" // 函数参数解构 function printPerson({ name, age }) { console.log(`${name} is ${age} years old`); }

模板字符串

const name = "张三"; const age = 25; // 传统字符串拼接 const message1 = "我叫" + name + ",今年" + age + "岁"; // 模板字符串 const message2 = `我叫${name},今年${age}岁`; // 多行字符串 const multiLine = ` 这是第一行 这是第二行 这是第三行 `;

类和继承

// 类定义 class Person { constructor(name, age) { this.name = name; this.age = age; } introduce() { return `我叫${this.name},今年${this.age}岁`; } // 静态方法 static create(name, age) { return new Person(name, age); } // getter get info() { return `${this.name} (${this.age})`; } // setter set info(value) { const [name, age] = value.split(' '); this.name = name; this.age = parseInt(age); } } // 继承 class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { return `${this.name}正在学习`; } }

Promise 和异步编程

// Promise 基础 const promise = new Promise((resolve, reject) => { setTimeout(() => { const random = Math.random(); if (random > 0.5) { resolve("成功!"); } else { reject("失败!"); } }, 1000); }); promise .then(result => console.log(result)) .catch(error => console.error(error)); // async/await async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } catch (error) { console.error('获取数据失败:', error); } } // Promise.all const promises = [ fetch('https://api.example.com/users'), fetch('https://api.example.com/posts'), fetch('https://api.example.com/comments') ]; Promise.all(promises) .then(responses => Promise.all(responses.map(r => r.json()))) .then(data => console.log(data));

函数式编程

高阶函数

// 高阶函数:接受函数作为参数或返回函数 function withLogging(fn) { return function(...args) { console.log('函数开始执行'); const result = fn(...args); console.log('函数执行完成'); return result; }; } const add = (a, b) => a + b; const addWithLogging = withLogging(add); // 函数柯里化 function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...moreArgs) { return curried.apply(this, args.concat(moreArgs)); }; }; } const curriedAdd = curry((a, b, c) => a + b + c); console.log(curriedAdd(1)(2)(3)); // 6

数组方法

const numbers = [1, 2, 3, 4, 5]; // map - 转换数组元素 const doubled = numbers.map(n => n * 2); // filter - 过滤数组元素 const evenNumbers = numbers.filter(n => n % 2 === 0); // reduce - 归约数组 const sum = numbers.reduce((total, n) => total + n, 0); // find - 查找元素 const firstEven = numbers.find(n => n % 2 === 0); // some - 检查是否有元素满足条件 const hasEven = numbers.some(n => n % 2 === 0); // every - 检查是否所有元素都满足条件 const allPositive = numbers.every(n => n > 0);

异步编程

回调函数

// 回调地狱示例 fs.readFile('file1.txt', 'utf8', (err, data1) => { if (err) return console.error(err); fs.readFile('file2.txt', 'utf8', (err, data2) => { if (err) return console.error(err); fs.writeFile('output.txt', data1 + data2, (err) => { if (err) return console.error(err); console.log('文件写入成功'); }); }); });

Promise 链式调用

// 使用 Promise 解决回调地狱 readFile('file1.txt') .then(data1 => readFile('file2.txt')) .then(data2 => writeFile('output.txt', data1 + data2)) .then(() => console.log('文件写入成功')) .catch(err => console.error(err));

async/await

// 使用 async/await 简化异步代码 async function processFiles() { try { const data1 = await readFile('file1.txt'); const data2 = await readFile('file2.txt'); await writeFile('output.txt', data1 + data2); console.log('文件写入成功'); } catch (err) { console.error(err); } }

DOM 操作

选择元素

// 选择单个元素 const element = document.getElementById('myId'); const elementByClass = document.querySelector('.myClass'); const elementByTag = document.querySelector('div'); // 选择多个元素 const elements = document.getElementsByClassName('myClass'); const elementsByTag = document.getElementsByTagName('div'); const elementsByQuery = document.querySelectorAll('.myClass');

修改元素

// 修改内容 element.textContent = '新文本内容'; element.innerHTML = '<span>HTML内容</span>'; // 修改属性 element.setAttribute('class', 'newClass'); element.className = 'newClass'; element.classList.add('newClass'); element.classList.remove('oldClass'); element.classList.toggle('toggleClass'); // 修改样式 element.style.color = 'red'; element.style.fontSize = '16px';

事件处理

// 添加事件监听器 element.addEventListener('click', function(event) { console.log('元素被点击了'); event.preventDefault(); // 阻止默认行为 }); // 移除事件监听器 const handler = function(event) { console.log('处理事件'); }; element.addEventListener('click', handler); element.removeEventListener('click', handler); // 事件委托 document.addEventListener('click', function(event) { if (event.target.matches('.button')) { console.log('按钮被点击了'); } });

模块化

ES6 模块

// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; export default function multiply(a, b) { return a * b; } // main.js import multiply, { add, subtract } from './math.js'; console.log(add(5, 3)); // 8 console.log(subtract(5, 3)); // 2 console.log(multiply(5, 3)); // 15

CommonJS 模块(Node.js)

// math.js const add = (a, b) => a + b; const subtract = (a, b) => a - b; module.exports = { add, subtract }; // main.js const { add, subtract } = require('./math.js');

最佳实践

错误处理

// try-catch try { const result = riskyOperation(); console.log(result); } catch (error) { console.error('操作失败:', error.message); } finally { console.log('清理工作'); } // 自定义错误 class CustomError extends Error { constructor(message, code) { super(message); this.name = 'CustomError'; this.code = code; } } throw new CustomError('自定义错误', 'CUSTOM_001');

性能优化

// 防抖函数 function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } // 节流函数 function throttle(func, delay) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= delay) { lastCall = now; func.apply(this, args); } }; } // 使用示例 const debouncedSearch = debounce(searchFunction, 300); const throttledScroll = throttle(scrollHandler, 100);

代码组织

// 立即执行函数表达式 (IIFE) (function() { const privateVariable = '私有变量'; function privateFunction() { console.log(privateVariable); } // 暴露公共接口 window.publicAPI = { publicFunction: privateFunction }; })(); // 模块模式 const module = (function() { const privateVariable = '私有变量'; function privateFunction() { console.log(privateVariable); } return { publicFunction: privateFunction }; })();

常用框架

React

import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = `计数: ${count}`; }, [count]); return ( <div> <p>当前计数: {count}</p> <button onClick={() => setCount(count + 1)}> 增加 </button> </div> ); }

Vue.js

import { createApp } from 'vue'; const app = createApp({ data() { return { count: 0 }; }, methods: { increment() { this.count++; } }, template: ` <div> <p>当前计数: {{ count }}</p> <button @click="increment">增加</button> </div> ` }); app.mount('#app');

Node.js

const express = require('express'); const app = express(); app.use(express.json()); app.get('/api/users', (req, res) => { res.json([ { id: 1, name: '张三' }, { id: 2, name: '李四' } ]); }); app.post('/api/users', (req, res) => { const { name } = req.body; res.status(201).json({ id: 3, name }); }); app.listen(3000, () => { console.log('服务器运行在端口 3000'); });

学习资源

常用工具

  • VS Code - 推荐的代码编辑器
  • Chrome DevTools - 浏览器调试工具
  • npm/yarn - 包管理器
  • Webpack/Vite - 构建工具
  • ESLint/Prettier - 代码质量工具

最后更新: 2024年

最近更新:12/9/2025, 2:17:56 AM