下面是 JavaScript 中常见的三个面试高频考点:
✅ 一、防抖(Debounce)
📌 场景:
- 例如搜索输入框,每次输入触发搜索太频繁;
- 希望用户停止操作后一段时间再触发函数。
✅ 实现方式:
ini
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
✅ 使用方式:
javascript
window.addEventListener('resize', debounce(() => {
console.log('窗口大小变化,执行逻辑');
}, 500));
✅ 二、节流(Throttle)
📌 场景:
- 例如滚动监听、按钮点击,频繁触发但希望控制执行频率;
- 比如希望每 500ms 执行一次即可。
✅ 时间戳实现:
ini
function throttle(fn, delay = 300) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime > delay) {
lastTime = now;
fn.apply(this, args);
}
};
}
✅ 使用方式:
javascript
document.addEventListener('scroll', throttle(() => {
console.log('节流执行 scroll');
}, 200));
✅ 三、数组扁平化(Flatten Array)
📌 场景:
- 嵌套数组
[1, [2, [3, [4]]]]
要变成[1, 2, 3, 4]
✅ 方法 1:递归实现
javascript
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
✅ 方法 2:flat(Infinity)
(ES10 简洁)
ini
const arr = [1, [2, [3, [4]]]];
const result = arr.flat(Infinity);
✅ 方法 3:迭代 + 栈实现(不使用递归)
arduino
function flatten(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.unshift(item); // 反顺序需要 unshift
}
}
return result;
}
✅ 总结对比
技术 | 适用场景 | 核心原理 |
---|---|---|
防抖 | 停止输入后再处理 | 每次都清定时器 |
节流 | 控制频繁触发频率 | 设置时间戳或定时器 |
扁平化 | 处理嵌套数组 | 递归 / ES10 flat / 栈 |