Z
ZHANK
🟨

JavaScript 速查表

JS 语法、数组方法、对象操作、异步编程、DOM 操作、ES6+ 特性速查

JavaScript 速查表

变量声明

const PI = 3.14;            // 常量——不能重新赋值
let count = 0;              // 变量——块作用域
// var name = "old";        // ❌ 避免使用

// 类型
typeof "hello"   // "string"
typeof 42        // "number"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object"(历史 bug)
typeof {}        // "object"
typeof []        // "object"
Array.isArray([]) // true

字符串

const s = "Hello, World!";
s.length                    // 13
s.toUpperCase()             // "HELLO, WORLD!"
s.toLowerCase()             // "hello, world!"
s.trim()                    // 去除首尾空格
s.split(", ")               // ["Hello", "World!"]
s.replace("World", "JS")    // "Hello, JS!"
s.includes("Hello")         // true
s.indexOf("World")          // 7
s.slice(0, 5)               // "Hello"
s.substring(7, 12)          // "World"

// 模板字符串
const name = "小明";
`Hello, ${name}!`

数组

const arr = [1, 2, 3, 4, 5];

// 增删
arr.push(6);                // 末尾添加 → [1,2,3,4,5,6]
arr.pop();                  // 末尾删除 → 返回 6
arr.unshift(0);             // 头部添加 → [0,1,2,3,4,5]
arr.shift();                // 头部删除 → 返回 0

// 遍历
arr.forEach((v, i) => console.log(i, v));
arr.map(v => v * 2);        // [2,4,6,8,10]
arr.filter(v => v > 2);     // [3,4,5]
arr.find(v => v > 3);       // 4(第一个匹配)
arr.findIndex(v => v > 3);  // 3
arr.some(v => v > 4);       // true(存在)
arr.every(v => v > 0);      // true(全部)
arr.reduce((a, b) => a + b, 0);  // 15

// 其他
arr.includes(3);            // true
arr.indexOf(3);             // 2
arr.slice(1, 3);            // [2,3]
arr.splice(2, 1);           // 删除索引2的1个元素
arr.join(", ");             // "1, 2, 3, 4, 5"
arr.sort((a, b) => a - b);  // 升序排序
[...arr1, ...arr2];         // 合并

对象

const obj = { name: "小明", age: 25 };
obj.name                    // "小明"
obj["age"]                  // 25
Object.keys(obj)            // ["name", "age"]
Object.values(obj)          // ["小明", 25]
Object.entries(obj)         // [["name","小明"], ["age",25]]

// 解构
const { name, age } = obj;
const { name: userName } = obj;  // 重命名
const { city = "北京" } = obj;   // 默认值

// 展开
const copy = { ...obj, age: 26 };  // 浅拷贝+覆盖

函数

// 函数声明
function add(a, b) { return a + b; }

// 箭头函数
const add = (a, b) => a + b;
const double = x => x * 2;
const greet = () => "Hello";

// 默认参数
function greet(name = "世界") { return `Hello, ${name}!`; }

// rest 参数
function sum(...nums) { return nums.reduce((a,b)=>a+b); }

异步编程

// Promise
fetch("/api/data")
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));

// async/await
async function loadData() {
    try {
        const res = await fetch("/api/data");
        const data = await res.json();
        return data;
    } catch (err) {
        console.error(err);
    }
}

// Promise.all 并发
const [a, b] = await Promise.all([fetchA(), fetchB()]);

DOM 操作

// 选择
document.querySelector(".class");
document.querySelectorAll("div");
document.getElementById("id");
document.getElementsByClassName("class");

// 修改
el.textContent = "文本";
el.innerHTML = "<b>HTML</b>";
el.setAttribute("href", "https://...");
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("dark");
el.style.color = "red";

// 事件
el.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    console.log(e.target);
});

// 创建
const div = document.createElement("div");
parent.appendChild(div);
el.remove();

常用技巧

// 去重
[...new Set(arr)];

// 随机数
Math.floor(Math.random() * 100);  // 0-99

// 延时
setTimeout(() => {}, 1000);
setInterval(() => {}, 1000);

// JSON
JSON.stringify(obj);
JSON.parse(jsonStr);

// 深拷贝
JSON.parse(JSON.stringify(obj));  // 简单版
structuredClone(obj);             // 现代版

// 空值合并
const val = input ?? "默认值";     // null/undefined 时用默认