萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 核心語法速查 106 條:從基礎到 DOM、BOM、事件、AJAX

基礎語法 (1-15)

  1. 輸出:document.write("") / console.log() (推薦)
  2. 註釋:// 單行、/* 多行 */
  3. HTML DOM 順序:document → html → (head, body)
  4. BOM 層級:window → (navigator, screen, history, location, document)
  5. 表單元素值:document.getElementById("id").value
  6. 大小寫轉換:.toUpperCase() / .toLowerCase()
  7. 值類型:String, Number, Boolean, Null, Undefined, Object, Symbol, BigInt (ES2020)
  8. 字符轉數字:parseInt(), parseFloat(), Number(), +str
  9. 數字轉字符:String(num), num.toString(), ""+num
  10. 字符串長度:.length
  11. 字符串拼接:+、+=、模板字符串 \`\${var}\`
  12. 比較運算符:== (類型轉換)、=== (嚴格)、!=, !==, >, >=, <, <=
  13. 變量聲明:const (首選)、let、var (避免)
  14. 條件判斷:if/else、三元 ? :、switch
  15. 循環:for, while, do-while, for...of (可迭代), for...in (鍵名)

函數與作用域 (16-25)

  1. 函數聲明:function fn() {}、函數表達式 const fn = () => {}
  2. 參數預設值:function fn(a=1) {}
  3. 剩餘參數:function fn(...args) {}
  4. 解構賦值:const [a,b] = arr; const {x,y} = obj;
  5. 閉包:內部函數引用外部變量,形成閉包保留作用域
  6. IIFE:(() => {})() 創建隔離作用域
  7. this 綁定:默認/隱式/顯式 (call/apply/bind)/new/箭頭函數繼承外層
  8. 嚴格模式:"use strict" 禁止隱式全局、this 指向 undefined 等
  9. 模組:export/import (ESM)、module.exports/require (CommonJS)
  10. 錯誤處理:try/catch/finally, throw new Error()

DOM 操作核心 (26-45)

  1. 選取:document.getElementById, querySelector, querySelectorAll
  2. 創建:document.createElement, createTextNode, createDocumentFragment
  3. 插入:appendChild, insertBefore, prepend, append, before, after, replaceWith
  4. 刪除:remove(), parent.removeChild(child)
  5. 複製:cloneNode(true) (深複製含事件/子孫)
  6. 屬性:getAttribute, setAttribute, removeAttribute, hasAttribute, dataset
  7. 類名:classList.add/remove/toggle/contains/replace
  8. 樣式:element.style.prop = val, cssText, getComputedStyle(el)
  9. 內容:textContent (安全、快), innerHTML (解析 HTML, 風險), innerText (渲染後文本, 慢)
  10. 遍歷:parentNode, children, firstElementChild, nextElementSibling
  11. 事件:addEventListener(type, handler, options), removeEventListener, event.preventDefault(), stopPropagation(), event.target, currentTarget
  12. 事件委派:父元素綁定,if (e.target.matches(".child"))
  13. 表單:form.elements, form.submit(), form.reset(), input.value, input.checkValidity(), reportValidity()
  14. 選取範圍:Selection, Range, execCommand (棄用)
  15. 滾動:scrollTo, scrollBy, scrollIntoView, scrollTop/Left
  16. 尺寸座標:getBoundingClientRect(), offsetWidth/Height, clientWidth/Height, scrollWidth/Height

BOM 與瀏覽器 API (46-70)

  1. window.open/close, opener, parent, top, self, frames
  2. location.href/replace/assign/reload, location.search/hash/pathname, URLSearchParams
  3. history.pushState/replaceState/go/back/forward, popstate 事件
  4. navigator.userAgent, navigator.geolocation, navigator.onLine, navigator.clipboard
  5. screen.width/height, availWidth/Height, colorDepth
  6. localStorage/sessionStorage (同源、5MB、同步)、IndexedDB (異步、大容量)
  7. Cookie:document.cookie、HttpOnly、Secure、SameSite
  8. 定時器:setTimeout/clearTimeout, setInterval/clearInterval, requestAnimationFrame/cancelAnimationFrame
  9. 異步:Promise, async/await, fetch, XMLHttpRequest (舊)
  10. fetch 基礎:fetch(url, {method, headers, body}).then(r=>r.json())
  11. 錯誤處理:window.onerror, unhandledrejection 事件
  12. 性能:performance.now(), performance.mark/measure, PerformanceObserver
  13. Worker:new Worker("worker.js"), postMessage, onmessage, SharedArrayBuffer
  14. Service Worker:離線緩存、推送通知、背景同步
  15. WebSocket:new WebSocket(url), send, onmessage, close
  16. Canvas:getContext("2d"), 繪製路徑、圖片、文字、變換
  17. WebGL:getContext("webgl"), 三維渲染、著色器
  18. SVG:命名空間 https://www.w3.org/2000/svg, 矢量圖形
  19. File API:FileReader, Blob, URL.createObjectURL, 拖拽上傳

進階模式與最佳實踐 (71-106)

  1. 防抖:function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn.apply(this, a), ms); }; }
  2. 節流:function throttle(fn, ms) { let last = 0; return (...a) => { const now = Date.now(); if (now - last >= ms) { last = now; fn.apply(this, a); } }; }
  3. 深拷貝:JSON.parse(JSON.stringify(obj)) (不含函數/循環引用) / structuredClone(obj) (現代)
  4. 類型判斷:Array.isArray, Object.prototype.toString.call
  5. 數組去重:[...new Set(arr)]
  6. 扁平化:arr.flat(Infinity)
  7. 對象合併:{...a, ...b} (淺合併)
  8. 可選鏈:obj?.prop?.()
  9. 空值合併:a ?? b (a 為 null/undefined 才用 b)
  10. 邏輯賦值:a ||= b, a ??= b, a &&= b
  11. 私有欄位:class { #priv = 1; getPriv() { return this.#priv; } }
  12. 裝飾器 (Stage 3):@decorator class {}
  13. 頂層 await:模組中直接 await fetch()
  14. 動態導入:import("./module.js").then(m => ...)
  15. Import Maps:瀏覽器裸模組導入映射
  16. Web Components:customElements.define, Shadow DOM, HTML Templates
  17. IntersectionObserver:視口進入/離開檢測 (懶加載、曝光統計)
  18. ResizeObserver:元素尺寸變化檢測
  19. MutationObserver:DOM 變異監聽
  20. PerformanceObserver:性能指標觀測 (LCP, FID, CLS)
  21. Intl 國際化:new Intl.DateTimeFormat, NumberFormat, RelativeTimeFormat, PluralRules
  22. Temporal 提案 (未來):現代日期時間 API
  23. Records & Tuples 提案 (未來):不可變數據結構
  24. Pattern Matching 提案 (未來):match (val) { when ... }

學習建議

不要死記 106 條。建立知識圖譜:語言核心 → DOM/BOM → 異步/模組 → 工程化/工具鏈 → 新提案。實戰中遇到查閱,形成肌肉記憶。MDN Web Docs 是最權威、最新的參考手冊。

copyright © 萬盛學電腦網 all rights reserved