⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

JS 调试技巧

学习 console.log/table/group/error 和 debugger · 难度:入门 · +10XP

JavaScript 调试技巧大全

JavaScript 调试(Debugging)是开发过程中不可或缺的技能。掌握高效的调试方法和工具可以大幅减少排查问题的时间,提升开发效率。现代浏览器提供了强大的开发者工具(DevTools),配合正确的调试策略,可以快速定位和修复 bug。

调试方法概览

方法适用场景说明
console.log()快速查看变量值最基础、最常用的方法
console.table()查看数组/对象结构化数据表格形式显示更清晰
console.time() / timeEnd()性能测量测量代码执行耗时
console.trace()查看函数调用堆栈理解调用路径
console.assert()条件断言只在条件为 false 时输出
debugger 语句设置断点代码执行到此自动暂停
浏览器断点复杂调试DevTools 中精确控制执行

console 高级用法

  1. 使用不同日志级别区分信息重要性
  2. 利用占位符格式化输出
  3. 对对象使用 console.dir() 查看完整属性
// 基本日志
console.log("普通日志");
console.warn("警告信息");
console.error("错误信息");
console.info("提示信息");

// 格式化输出 const user = { name: "张三", age: 25 }; console.log("用户 %s 的年龄是 %d 岁", user.name, user.age); console.log("用户对象:", user);

// console.table 表格输出(非常适合数组对象) const users = [ { id: 1, name: "张三", role: "admin" }, { id: 2, name: "李四", role: "user" } ]; console.table(users);

// 性能测量 console.time("循环耗时"); for (let i = 0; i < 1000000; i++) { /* 耗时操作 */ } console.timeEnd("循环耗时"); // "循环耗时: 3.2ms"

// 调用堆栈追踪 function a() { b(); } function b() { c(); } function c() { console.trace("当前调用堆栈"); } a(); // 打印从 a -> b -> c 的完整调用链

// 条件断言(仅在条件为 false 时输出) console.assert(1 === 2, "断言失败!1 不等于 2");

浏览器开发者工具调试

// debugger 语句:代码中设置断点
function calculateTotal(items) {
  let total = 0;
  for (const item of items) {
    debugger; // 执行到此处自动暂停,可在 DevTools 中检查变量
    total += item.price * item.quantity;
  }
  return total;
}

// 在浏览器 DevTools 中你可以: // 1. F12 打开开发者工具 -> Sources 面板 // 2. 点击行号设置断点 // 3. 右键断点设置条件断点(如:item.price > 100) // 4. 使用 Watch 面板实时查看表达式结果 // 5. 在 Console 面板中直接修改变量值 // 6. 使用 Call Stack 面板查看调用链 // 7. Scope 面板查看所有作用域变量

常用调试技巧与工具

// 1. 全局错误捕获
window.onerror = function(message, source, line, col, error) {
  console.error("全局错误:", message, "at", source + ":" + line);
  // 可上报到错误监控服务
};
window.addEventListener("unhandledrejection", event => {
  console.error("未处理的 Promise 拒绝:", event.reason);
});

// 2. 条件日志:只在开发环境输出 const DEBUG = true; function debugLog(...args) { if (DEBUG) console.log("[DEBUG]", ...args); } debugLog("这行只在 DEBUG=true 时才输出");

// 3. 监控特定对象变化 const obj = { value: 1 }; // 在 DevTools Console 中右键对象 -> "Store as global variable" // 然后使用 temp1 变量名访问

// 4. 模拟慢网络 // DevTools -> Network -> Throttling -> Slow 3G

// 5. 使用 debug() 函数(在 DevTools Console 中) // debug(someFunction); // 每次调用 someFunction 时自动进入断点 // undebug(someFunction); // 取消

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0