2024-12-25-JavaScript / TypeScript 语法速记

First Post:

Last Update:

Page View: loading...

JavaScript / TypeScript 语法速记表

变量声明

1
2
3
4
5
6
// ES5
var x = 10; // 函数作用域

// ES6+
let y = 20; // 块级作用域,可重新赋值
const z = 30; // 块级作用域,不可重新赋值

数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 基本类型
let str: string = "Hello";
let num: number = 42;
let bool: boolean = true;
let undef: undefined = undefined;
let nul: null = null;
let sym: symbol = Symbol("id");

// 引用类型
let obj: object = { key: "value" };
let arr: number[] = [1, 2, 3];
let func: Function = () => {};

// TS特有类型
let anyType: any = "anything"; // 任意类型
let tuple: [string, number] = ["a", 1]; // 元组
enum Color {
Red,
Green,
Blue,
} // 枚举
let unknownType: unknown; // 未知类型
let neverType: never; // 永不存在的值
let voidType: void; // 无返回值

运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 算术运算符
+ - * / % ** ++ --

// 比较运算符
== === != !== > < >= <=

// 逻辑运算符
&& || !

// 赋值运算符
= += -= *= /= %=

// ES6新增
?? // 空值合并
?. // 可选链
... // 展开/剩余运算符

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 函数声明
function add(a: number, b: number): number {
return a + b;
}

// 函数表达式
const multiply = function (a, b) {
return a * b;
};

// 箭头函数
const divide = (a, b) => a / b;
const sayHi = () => console.log("Hi");

// 参数默认值
function greet(name = "Guest") {}

// 剩余参数
function sum(...numbers) {}

// TS函数类型
type AddFunc = (a: number, b: number) => number;

类与面向对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 类定义
class Animal {
// 属性
name: string;
private age: number;
protected species: string;
static count: number = 0;

// 构造函数
constructor(name: string) {
this.name = name;
}

// 方法
speak(): void {
console.log("Sound");
}

// Getter/Setter
get getAge(): number { return this.age; }
set setAge(value: number) { this.age = value; }
}

// 继承
class Dog extends Animal {
bark(): void {
console.log("Woof!");
}

// 方法重写
override speak(): void {
console.log("Woof!");
}
}

// 抽象类 (TS)
abstract class Shape {
abstract area(): number;
}

// 接口 (TS)
interface Person {
name: string;
age: number;
greet(): void;
}

// 实现接口
class Student implements Person {
name: string;
age: number;
greet() { console.log("Hello"); }
}

数组操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 数组方法
arr.push(), arr.pop(), arr.shift(), arr.unshift();
arr.map(), arr.filter(), arr.reduce(), arr.forEach();
arr.find(), arr.findIndex(), arr.some(), arr.every();
arr.slice(), arr.splice(), arr.concat(), arr.join();
arr.sort(), arr.reverse();

// 解构赋值
const [first, ...rest] = [1, 2, 3];
const { name, age } = person;

// 扩展运算符
const newArr = [...oldArr, 4];
const newObj = { ...oldObj, key: "value" };

对象操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 对象字面量增强
const name = "John";
const person = { name, age: 30 }; // 属性简写
const obj = { ["key" + 1]: "value" }; // 计算属性名

// 方法简写
const obj = {
method() {
return this;
},
};

// 对象方法
Object.keys(obj), Object.values(obj), Object.entries(obj);
Object.assign(target, source);
Object.freeze(obj);
Object.seal(obj);

异步编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});

promise
.then((result) => console.log(result))
.catch((error) => console.error(error))
.finally(() => console.log("Complete"));

// Async/Await
async function fetchData() {
try {
const data = await fetch(url);
const result = await data.json();
return result;
} catch (error) {
console.error(error);
}
}

// Promise方法
Promise.all([p1, p2]);
Promise.race([p1, p2]);
Promise.allSettled([p1, p2]);
Promise.any([p1, p2]);

模块系统

1
2
3
4
5
6
7
8
9
10
11
// 导出
export const PI = 3.14;
export function add() {}
export default class MyClass {}
export { var1, var2 as alias };

// 导入
import MyClass from "./module";
import { var1, var2 as alias } from "./module";
import * as Module from "./module";
import("./module").then((module) => {}); // 动态导入

字符串

1
2
3
4
5
6
7
8
9
// 模板字符串
const greeting = `Hello ${name}, you are ${age} years old`;

// 字符串方法
str.includes(), str.startsWith(), str.endsWith();
str.repeat(), str.padStart(), str.padEnd();
str.trim(), str.trimStart(), str.trimEnd();
str.replace(), str.replaceAll();
str.slice(), str.substring(), str.substr();

类型操作 (TypeScript)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 类型注解
let x: number = 5;

// 类型别名
type ID = string | number;
type User = { id: ID; name: string };

// 联合类型
let value: string | number;

// 交叉类型
type Combined = TypeA & TypeB;

// 类型断言
let str = value as string;
let len = (<string>value).length;

// 泛型
function identity<T>(arg: T): T {
return arg;
}
interface Generic<T> {
value: T;
}

// 条件类型
type IsString<T> = T extends string ? true : false;

// 映射类型
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Partial<T> = { [K in keyof T]?: T[K] };

错误处理

1
2
3
4
5
6
7
8
9
// Try-Catch
try {
// 可能出错的代码
throw new Error("Something went wrong");
} catch (error) {
console.error(error);
} finally {
// 始终执行
}

ES6+ 新特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 解构赋值
const { a, b } = obj;
const [x, y] = arr;

// 默认参数
function f(x = 1, y = 2) {}

// 剩余参数
function f(...args) {}

// 可选链
const value = obj?.prop?.nested;

// 空值合并
const result = input ?? "default";

// BigInt
const big = 9007199254740991n;

// 动态导入
import("./module.js").then((module) => {});

常用数组/对象方法链

1
2
3
4
5
6
// 常见处理模式
array
.filter((item) => item.active)
.map((item) => ({ ...item, processed: true }))
.sort((a, b) => a.id - b.id)
.reduce((acc, curr) => acc + curr.value, 0);

实用代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 深拷贝
const deepCopy = JSON.parse(JSON.stringify(obj));
// 或
const deepCopy = structuredClone(obj);

// 去重
const unique = [...new Set(array)];

// 对象合并
const merged = Object.assign({}, obj1, obj2);
// 或
const merged = { ...obj1, ...obj2 };

// 检查空对象
const isEmpty = Object.keys(obj).length === 0;

// 延迟执行
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 节流防抖
const debounce = (func, wait) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};

constructor 关键字

constructor 是类(class)中用于定义构造函数的关键字。构造函数是一种特殊的方法,在使用 new 创建类实例时自动调用,用于初始化对象的属性和状态。

  • 作用
    • 初始化新创建的对象。
    • 可接受参数,用于设置实例的初始值。
    • 如果类中未显式定义 constructor,JavaScript 会提供一个默认的空构造函数。
  • 语法示例(TypeScript/JavaScript):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Person {
    name: string;
    age: number;

    // 构造函数
    constructor(name: string, age: number) {
    this.name = name; // 初始化实例属性
    this.age = age;
    }

    greet() {
    console.log(`Hello, my name is ${this.name}`);
    }
    }
  • 特点

    • 一个类中只能有一个名为 constructor 的方法,否则会抛出语法错误。
    • 在继承中,可通过 super() 调用父类的构造函数。

new 关键字

new 是用于创建对象实例的操作符关键字。它与构造函数结合使用,执行类的实例化过程。

  • 作用
    • 创建一个新对象。
    • 将构造函数的 this 绑定到新对象。
    • 执行构造函数代码。
    • 如果构造函数未显式返回对象,则返回新创建的对象。
  • 执行步骤(内部机制):
    1. 创建一个空对象 {}。
    2. 将该对象的原型(proto)设置为构造函数的 prototype。
    3. 将 this 绑定到新对象并调用构造函数。
    4. 返回该对象(除非构造函数返回其他对象)。
  • 语法示例
    1
    2
    const person = new Person('Alice', 30);  // 使用 new 调用构造函数创建实例
    person.greet(); // 输出: Hello, my name is Alice
  • 常见错误
    • 直接调用构造函数而不使用 new(如 Person(‘Alice’, 30)),会导致 this 指向全局对象(严格模式下为 undefined),可能造成意外行为。

两者关系

  • new 操作符触发类的 constructor 方法执行。
  • 它们共同实现了 JavaScript 的类实例化机制,支持原型继承和面向对象编程范式。

在 TypeScript 中,这些关键字的行为与 JavaScript 完全一致,但 TypeScript 通过类型注解提供了更强的静态类型检查,提升了代码的安全性和可维护性。


DST:

  1. const > let > var​ 优先使用 const
  2. === 代替 == 严格相等判断
  3. 箭头函数保持 this 绑定
  4. 模板字符串代替拼接
  5. 解构简化代码
  6. Promise 处理异步,async/await 更可读
  7. 可选链和空值合并处理 null/undefined