1.什么是HMR
HMR是Hot Module Rplacement的缩写,即为热模块替换,也叫热重载,是一种应用于开发阶段,通过webpack或者vite等构建工具在不刷新页面的情况下,对我们修改的文件进行替换到浏览器的技术,使得我们在开发过程中实现代码修改即可呈现在页面的行为,加快调试速度,HMR在各个构建工具的实现是不一样的,但是他们核心的原理都是通过监控文件的变更后,把文件通过websocket推送给浏览器
2.对象数组去重
当对象完全相同时:使用JSON将对象转换为字符串,并使用Set去除重复项,完成后再使用JSON格式化对象,再使用from方法转换Set对象为数组
const a = [
{ code: "1", value: "a" },
{ code: "2", value: "b" },
{ code: "3", value: "c" },
];
const b = [
{ code: "3", value: "c" },
{ code: "4", value: "e" },
];
const newArr = [...a, ...b];
const res = Array.from(new Set(newArr.map((obj) => JSON.stringify(obj)))).map(
(str) => JSON.parse(str)
);
当对象只有其中关键属性相同时:使用Array.prototype.map(item => [item.code, item])方法遍历出一个键值对数组,然后通过Map去重,再把Map还原为数组即可
const a = [
{ code: "1", value: "a" },
{ code: "2", value: "b" },
{ code: "3", value: "c" },
];
const b = [
{ code: "3", value: "d" },
{ code: "4", value: "e" },
];
const newArray = [...a,...b];
const res = [...new Map(newArray.map(item => [item.code, item])).values()]
3.展开嵌套数组
最简单的方法是使用Array.prototype.flat()方法
const nestedArray = [1, [2], [[3]]];
console.log(nestedArray.flat(Infinity));
使用递归的方法:
const nestedArray = [1, [2], [[3]]];
function flatten(arr) {
return arr.reduce(
(acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur),
[]
);
}
4.反转链表
三指针法:
function reverseLinkedList(head){
const prev = null;
const current = head;
while(!current){
let next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
5.二维数组最小路径和
动态规划:
function minPathSum(grid) {
const m = grid.length;
const n = grid[0].length;
for (let i = 1; i < m; i++) {
grid[i][0] += grid[i - 1][0];
}
for (let j = 1; j < n; j++) {
grid[0][j] += grid[0][j - 1];
}
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[m - 1][n - 1];
}
评论区