更新于 

Ts/Js 机巧收藏篇

记录其 Ts/Js 通用技巧

需求

扩展全局作用域
  • 使用 declare global
合并数组和对象
  • 数组对象可以使用数组的concat方法或者扩展运算符...来合并
  • 普通对象可以使用对象的assign方法或者扩展运算符...来合并
删除 Json 中不想要的字段和值
  • 使用delete操作符
数组内实现删除/插入/保留等逻辑
  • 删除指定下标对象: arr.splice(index,1)
  • 在指定下标插入对象: arr.splice(index, 0, 对象)
  • 在指定下标替换对象: arr.splice(index, 1, 对象)
  • 保留多少个对象: arr.splice(个数)
属性映射和类型约束
  • Record
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type petsGroup = "dog" | "cat" | "fish";
interface IPetInfo {
name: string;
age: number;
}
type IPets = Record<petsGroup, IPetInfo>;

type Animal = "Dog" | "Cat" | "Bird";
const animalContent: Record<Animal, JSX.Element> = {
Dog: <div>Dog is loyal and friendly.</div>,
Cat: <div>Cat is cute and independent.</div>,
Bird: <div>Bird is colorful and free.</div>,
};

function getAnimalContent(animal: Animal) {
return animalContent[animal];
}
帧率显示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let last = Date.now();
let ticks = 0;
function rafLoop(timestamp) {
ticks += 1;
if (ticks >= 30) {
const now = Date.now();
const diff = now - last
const fps = Math.round(1000 / (diff / ticks));
last = now
ticks = 0
renderFps(fps)
}
requestAnimationFrame(rafLoop);
}

let fpsEl = document.getElementById('fps');
function renderFps(fps) {
fpsEl.textContent = fps;
}
rafLoop();
异步逻辑
1
2
3
return new Promise((resolve) => {
resolve(1);
});