JavaScript 语法解析
一、基础语法结构
变量声明
let:声明可重新赋值的块级作用域变量const:声明不可重新赋值的常量(对象属性可变)let count = 10; // 可修改 count = 20; // 合法 const PI = 3.14; // 常量 PI = 3; // 报错:Assignment to constant variable
数据类型
- 原始类型:
String,Number,Boolean,null,undefined,Symbol,BigInt 引用类型:
Object,Array,Function,Date等// 类型检测 typeof "Hello"; // "string" Array.isArray([]); // true NaN === NaN; // false(特殊值)
- 原始类型:
运算符
逻辑运算符:
&&(与),||(或),??(空值合并)const name = userInput || "Guest"; // 默认值 const value = nullableVar ?? 100; // 空值合并
二、流程控制
条件语句
// if-else if (score >= 90) grade = 'A'; else if (score >= 60) grade = 'C'; else grade = 'F'; // switch switch (day) { case 1: dayName = "周一"; break; case 2: dayName = "周二"; break; default: dayName = "周末"; }循环结构
// for循环 for (let i = 0; i < 5; i++) { console.log(i); } // for...of 遍历数组 for (const item of ['a', 'b', 'c']) { console.log(item); } // while循环 while (condition) { ... }错误处理
try { JSON.parse(invalidJson); // 可能抛出错误 } catch (err) { console.error("解析失败:", err.message); } finally { console.log("清理工作"); }三、函数与作用域
函数定义
// 函数声明 function add(a, b) { return a + b; } // 箭头函数(无自己的this) const multiply = (a, b) => a * b; // 立即执行函数(IIFE) (function() { console.log("立即执行"); })();闭包
function createCounter() { let count = 0; return function() { return ++count; // 访问外部作用域的count }; } const counter = createCounter(); counter(); // 1 counter(); // 2
四、面向对象编程
类与继承
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} 发出声音`); } } class Dog extends Animal { speak() { super.speak(); // 调用父类方法 console.log("汪汪!"); } } const dog = new Dog("Buddy"); dog.speak(); // "Buddy 发出声音" + "汪汪!"原型链
// 构造函数 function Person(name) { this.name = name; } // 原型方法 Person.prototype.greet = function() { console.log(`你好, ${this.name}`); }; const john = new Person("John"); john.greet(); // "你好, John"
五、异步编程
Promise
function fetchData(url) { return new Promise((resolve, reject) => { fetch(url) .then(response => { if (response.ok) resolve(response.json()); else reject("请求失败"); }) .catch(error => reject(error)); }); } fetchData('/api/data') .then(data => console.log(data)) .catch(err => console.error(err));Async/Await
async function getUserData(userId) { try { const user = await fetch(`/users/${userId}`); const posts = await fetch(`/posts?userId=${userId}`); return { user, posts }; } catch (error) { console.error("加载失败:", error); return null; } }
六、DOM 操作
元素操作
// 选择元素 const btn = document.getElementById('submitBtn'); // 事件监听 btn.addEventListener('click', () => { const input = document.querySelector('input[name="email"]'); console.log(input.value); // 修改样式 btn.style.backgroundColor = "blue"; // 创建新元素 const newItem = document.createElement('li'); newItem.textContent = "新项目"; document.getElementById('list').appendChild(newItem); });AJAX 请求
fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }) .then(response => response.json()) .then(data => { document.getElementById('result').innerText = data.result; });
七、现代语法特性
解构赋值
// 对象解构 const { name, age } = user; // 数组解构 const [first, , third] = ['a', 'b', 'c']; // 函数参数解构 function printUser({ name, age = 18 }) { console.log(`${name}, ${age}岁`); }展开运算符
// 数组合并 const combined = [...arr1, ...arr2]; // 对象合并 const mergedObj = { ...defaults, ...userSettings }; // 函数参数 Math.max(...numbers);可选链与空值合并
// 安全访问嵌套属性 const street = user?.address?.street ?? "未知街道"; // 安全调用方法 const result = obj.method?.();
八、模块化
ES Modules
// math.js export const sum = (a, b) => a + b; export default function multiply(a, b) { return a * b; } // app.js import mult, { sum } from './math.js'; console.log(sum(2, 3), mult(2, 3)); // 5, 6
九、实用代码片段
数组操作
// 转换 const squares = [1, 2, 3].map(x => x * x); // [1, 4, 9] // 过滤 const evens = [1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4] // 查找 const user = users.find(u => u.id === 123);日期处理
const now = new Date(); console.log(now.toLocaleDateString()); // "2023/7/23" // 时间戳 const timestamp = Date.now();本地存储
// 保存数据 localStorage.setItem('theme', 'dark'); // 读取数据 const theme = localStorage.getItem('theme') || 'light';
JavaScript 执行流程图
graph LR
A[代码加载] --> B[解析语法]
B --> C[创建执行上下文]
C --> D[变量提升]
D --> E[执行同步代码]
E --> F{有异步操作?}
F -- 是 --> G[放入任务队列]
F -- 否 --> H[继续执行]
G --> I[事件循环检查]
I --> J[调用栈空闲?]
J -- 是 --> K[执行微任务]
K --> L[执行宏任务]
L --> I
J -- 否 --> E
评论