js手写题
1. 手写防抖(debounce)和节流(throttle)
-
防抖
function debounce(fn, delay) { let timer = null; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }
-
节流
function throttle(fn, interval) { let lastTime = 0; return function(...args) { const now = Date.now(); if (now - lastTime >= interval) { fn.apply(this, args); lastTime = now; } }; }
2. 手写深拷贝
function deepClone(obj, map = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj
if (map.has(obj)) return map.get(obj) //解决循环引用
const cloneObj = Array.isArray(obj) ? [] : {};
map.set(obj, cloneObj);
// 遍历所有属性(包括不可枚举、Symbol 键)
Reflect.ownKeys(obj).forEach(key => {
cloneObj[key] = deepClone(obj[key], map);
});
return cloneObj;
}
3. 手写数组扁平化
// 递归实现
function flatArr(arr, depth = Infinity) {
const res = [];
arr.forEach(item => {
if (Array.isArray(item) && depth > 0) {
res.push(...flatArr(item, depth - 1));
} else {
res.push(item);
}
});
return res;
}
4. 手写数组去重
// 简洁版(ES6)
function uniqueArr(arr) {
return [...new Set(arr)];
}
// 兼容版(处理对象/NaN)
function uniqueArr(arr) {
const map = new Map();
return arr.filter(item => !map.has(item) && map.set(item, true));
}