在线代码运行BanShow Run

JavaScript 语法速查表

JavaScript 语法速查表,按知识点分节整理常用写法,每段示例都能直接复制到上面的编辑器里运行验证。适合初学 JavaScript 时随手查阅,不用装任何环境。

打开 JavaScript 运行器 →

变量与声明

javascript
let count = 1;          // 可以重新赋值
const name = "小明";     // 常量,不能重新赋值(但对象内部可以改)
var old = "别用了";      // 老写法,有作用域提升问题

count = 2;              // OK
// name = "小红";        // TypeError: Assignment to constant variable

const user = { age: 18 };
user.age = 19;          // OK:改的是对象属性,不是重新赋值 user

console.log(typeof count, typeof name, typeof undefined, typeof null);
console.log(typeof {}, typeof [], typeof function () {});

记住三条:优先用 const,需要改才用 let,永远不用 var。typeof null 是 "object"(历史遗留 bug)。数组的 typeof 也是 "object",判断数组要用 Array.isArray(x)。

基本类型与转换

javascript
console.log(1 + "2");        // "12"  字符串拼接优先
console.log(1 - "2");        // -1    减号会转数字
console.log("5" * 2, "6" / "2");
console.log(0.1 + 0.2);      // 0.30000000000000004  浮点数精度问题
console.log((0.1 + 0.2).toFixed(2));        // "0.30",注意返回字符串
console.log(Number((0.1 + 0.2).toFixed(2))); // 0.3

console.log(Number("42"), Number(""), Number("abc"), Number(true));
console.log(parseInt("42px"), parseFloat("3.14abc"));
console.log(String(42), (42).toString(), `${42}`);
console.log(Boolean(0), Boolean(""), Boolean(null), Boolean([]), Boolean("0"));

console.log(NaN === NaN, Number.isNaN(NaN));     // false, true
console.log(Infinity, -Infinity, 1 / 0);
console.log(Math.floor(3.7), Math.ceil(3.2), Math.round(3.5), Math.trunc(-3.7));
console.log(Number.MAX_SAFE_INTEGER, Number.isInteger(3.0));

要注意:[] 和 "0" 都是真值(truthy),只有 0 "" null undefined NaN false 这六个是假值。

字符串

javascript
const s = "Hello, JavaScript 世界";
console.log(s.length, s[0], s.at(-1));
console.log(s.toUpperCase(), s.toLowerCase());
console.log(s.slice(0, 5), s.slice(-2));
console.log(s.substring(0, 5));
console.log(s.indexOf("Script"), s.includes("Java"), s.startsWith("He"), s.endsWith("界"));
console.log(s.replace("Java", "TS"), s.replaceAll("a", "@"));
console.log("a,b,c".split(","), ["a", "b"].join("-"));
console.log("  x  ".trim(), "007".padStart(5, "0"), "hi".padEnd(5, "."));
console.log(s.split(""));          // 按字符拆成数组
console.log("ab".repeat(3));

// 模板字符串:反引号 + ${},可以换行
const n = 3;
console.log(`n 是 ${n},平方是 ${n * n}`);
console.log(`多行
文本`);
console.log(`${n > 2 ? "大于2" : "小于等于2"}`);

数组

javascript
const nums = [5, 2, 9, 1, 7];
console.log(nums.length, nums[0], nums.at(-1));

// 增删
const a = [...nums];
a.push(3);              // 末尾加,返回新长度
a.unshift(0);           // 开头加
a.pop();                // 删末尾,返回被删的元素
a.shift();              // 删开头
a.splice(1, 2);         // 从下标 1 开始删 2 个
a.splice(1, 0, 100);    // 在下标 1 插入 100
console.log(a);

// 遍历(不修改原数组的都返回新数组)
console.log(nums.map((x) => x * 2));
console.log(nums.filter((x) => x > 3));
console.log(nums.reduce((sum, x) => sum + x, 0));
console.log(nums.find((x) => x > 3), nums.findIndex((x) => x > 3));
console.log(nums.some((x) => x > 8), nums.every((x) => x > 0));
console.log(nums.includes(9), nums.indexOf(9));
console.log([[1, [2]], [3]].flat(2), [[1, [2, [3]]]].flat(Infinity));
console.log(nums.forEach((x) => console.log(" ", x)));   // forEach 返回 undefined

// 排序:默认按字符串比较,这是最常见的坑
console.log([10, 9, 1].sort());                 // [1, 10, 9]
console.log([10, 9, 1].sort((x, y) => x - y));  // [1, 9, 10]
console.log(nums.toSorted((x, y) => x - y));    // 不改原数组的新方法

// 拼接与去重
console.log([...nums, 3, 3], Array.from(new Set([...nums, 3, 3])));
console.log(nums.concat([8]), Array.of(1, 2, 3), Array(3).fill(0));
console.log(Array.from({ length: 5 }, (_, i) => i + 1));

对象

javascript
const user = { name: "小明", age: 18, city: "北京" };

console.log(user.name, user["age"]);
console.log(Object.keys(user), Object.values(user), Object.entries(user));
console.log("city" in user, user.email ?? "未填写");

// 增删改
user.email = "x@example.com";
delete user.city;

// 解构
const { name, age } = user;
const { name: userName, email = "无" } = user;    // 改名 + 默认值
const { ...rest } = user;                          // 剩余属性

// 展开与浅拷贝
const copy = { ...user, age: 20 };
const merged = Object.assign({}, user, { age: 21 });

// 计算属性名与方法简写
const key = "score";
const obj = { [key]: 90, greet() { return `你好,${this.name}`; } };
console.log(obj, obj.greet());

// 可选链:访问可能不存在的属性不会报错
console.log(user.address?.city?.length, obj.greet?.(), user.missing?.());

// 遍历
for (const [k, v] of Object.entries(user)) console.log(k, "=", v);
Object.keys(user).forEach((k) => console.log(k, user[k]));

Map 与 Set

javascript
const map = new Map();
map.set("a", 1).set("b", 2);
console.log(map.get("a"), map.has("b"), map.size);
map.delete("a");
for (const [k, v] of map) console.log(k, v);
console.log([...map.keys()], [...map.values()], Object.fromEntries(map));

const set = new Set([1, 2, 2, 3, 3]);
set.add(4);
console.log([...set], set.has(3), set.size);
console.log([...new Set("aabbc")].join(""));    // 字符串去重

// 和普通对象的区别:Map 的键可以是任意类型,且保持插入顺序
const m2 = new Map([[{ id: 1 }, "对象也能当键"]]);
console.log(m2.size);

条件与循环

javascript
const score = 76;
if (score >= 90) console.log("优秀");
else if (score >= 60) console.log("及格");
else console.log("不及格");

// 三元运算符
console.log(score >= 60 ? "通过" : "补考");

// switch:每个 case 记得 break,否则会"穿透"
switch (Math.floor(score / 10)) {
  case 9: console.log("A"); break;
  case 8: console.log("B"); break;
  case 7: console.log("C"); break;
  default: console.log("D");
}

for (let i = 0; i < 3; i++) console.log("i =", i);
for (const x of [1, 2, 3]) console.log("of 拿到值:", x);
for (const k in { a: 1, b: 2 }) console.log("in 拿到键:", k);

let n = 3;
while (n > 0) { n--; if (n === 1) continue; console.log("n =", n); }

// break / continue / 标签
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 2) break outer;      // 直接跳出两层循环
    console.log(i, j);
  }
}

**== 与 ===**:== 会做隐式类型转换,=== 严格比较。**永远用 === 和 !==**。

javascript
console.log(1 == "1", 1 === "1");        // true, false
console.log(null == undefined, null === undefined);   // true, false
console.log(0 == "", 0 == false, "" == false);        // 全是 true
console.log(NaN === NaN);                // false,判断 NaN 用 Number.isNaN

函数

javascript
function add(a, b = 0) { return a + b; }          // 默认参数
const sub = (a, b) => a - b;                       // 箭头函数,单表达式可省 return
const log = (...args) => console.log(args);        // 剩余参数
const noop = () => {};

console.log(add(1, 2), add(1), sub(5, 3));
log(1, "a", true);

// 解构参数
const greet = ({ name, age = 0 }) => `${name}(${age})`;
console.log(greet({ name: "小明" }));

// 高阶函数:接收函数或返回函数
const twice = (fn) => (x) => fn(fn(x));
console.log(twice((n) => n + 3)(10));

// 闭包:内层函数记住外层变量
function counter() {
  let n = 0;
  return { inc: () => ++n, get: () => n };
}
const c = counter();
c.inc(); c.inc();
console.log(c.get());

// this 与箭头函数:箭头函数没有自己的 this,用的是定义处外层的 this
const timer = {
  name: "计时器",
  ticks: 0,
  bumpTwice() {
    const bump = () => this.ticks++;      // 箭头函数继承 bumpTwice 的 this
    bump();
    bump();
    return `${this.name}: ${this.ticks}`;
  },
};
console.log(timer.bumpTwice());                                     // 计时器: 2
console.log(timer.bumpTwice.call({ name: "别的对象", ticks: 100 }));  // 手动指定 this

异步:Promise 与 async / await

javascript
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));

async function main() {
  console.log("开始");
  const a = await delay(300, "第一个结果");
  console.log(a);

  // 并发执行,比串行快
  const [b, c] = await Promise.all([delay(300, "B"), delay(300, "C")]);
  console.log(b, c);

  // 有一个失败也要拿到其他结果
  const results = await Promise.allSettled([
    delay(100, "成功"),
    Promise.reject(new Error("故意失败")),
  ]);
  console.log(results.map((r) => r.status));

  // 错误处理
  try {
    await Promise.reject(new Error("boom"));
  } catch (e) {
    console.log("捕获到:", e.message);
  }
  console.log("结束");
}

await main();     // 本站支持顶层 await,可以直接 await main()

要注意:忘记 await 是初学者最常犯的错——console.log(delay(100, "x")) 打印的是 Promise { <pending> } 而不是结果。

类

javascript
class Animal {
  #sound;                       // 私有字段,外部访问不到
  static count = 0;             // 静态属性

  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
    Animal.count++;
  }

  speak() { return `${this.name} 说:${this.#sound}`; }
  get info() { return `${this.name}(${this.constructor.name})`; }
  static create(name) { return new Animal(name, "…"); }
}

class Dog extends Animal {
  constructor(name) { super(name, "汪汪"); this.tricks = []; }
  learn(t) { this.tricks.push(t); return this; }        // 返回 this 支持链式调用
  speak() { return `${super.speak()}(会 ${this.tricks.length} 个动作)`; }
}

const d = new Dog("旺财");
d.learn("握手").learn("翻滚");
console.log(d.speak(), d.info, d instanceof Animal, Animal.count);
console.log(Object.keys(d));          // 私有字段不在里面

JSON 与正则

javascript
const data = { name: "小明", scores: [85, 92], meta: { city: "北京" } };
const text = JSON.stringify(data);
console.log(text);
console.log(JSON.stringify(data, null, 2));                 // 缩进美化
console.log(JSON.stringify(data, ["name", "scores"]));      // 只保留指定字段
console.log(JSON.parse(text).meta.city);
console.log(JSON.parse(text, (k, v) => (k === "scores" ? v.map((x) => x + 1) : v)));

try {
  JSON.parse("{坏掉的 json}");
} catch (e) {
  console.log("解析失败:", e.message);
}

// 正则:/模式/标志   g 全局  i 忽略大小写
const re = /\d+/g;
console.log("a1b22c333".match(re));
console.log("2026-10-04".replace(/-/g, "/"));
console.log(/^1[3-9]\d{9}$/.test("13812345678"));
console.log("a,b,,c".split(/,+/).filter(Boolean));
console.log(/(\w+)@(\w+)/.exec("hi@example")[1]);

常用内置对象

javascript
console.log(Math.max(1, 5, 3), Math.min(1, 5), Math.abs(-3), Math.pow(2, 10), 2 ** 10);
console.log(Math.random(), Math.floor(Math.random() * 10) + 1);   // 1-10 随机整数
console.log(Math.sqrt(16), Math.PI.toFixed(4));

const now = new Date();
console.log(now.getFullYear(), now.getMonth() + 1, now.getDate());   // 月份从 0 开始
console.log(now.toISOString(), now.toLocaleString("zh-CN"));
console.log(new Date("2026-10-04").getTime(), Date.now());

console.log(new Intl.NumberFormat("zh-CN", { style: "currency", currency: "CNY" }).format(1234.5));
console.log(new Intl.NumberFormat("zh-CN").format(1234567));
console.error("这是 stderr 输出");
console.warn("这是警告");
console.table([{ a: 1, b: 2 }, { a: 3, b: 4 }]);

换一门语言