防抖(Debounce)函数:
防抖函数会在一段连续的触发事件停止后执行一次,用于防止频繁触发事件造成性能问题。
function debounce(func, delay) { let timeoutId; return function (...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // 用法示例 const debouncedFunction = debounce(() => { console.log("防抖函数被触发"); }, 1000); // 在某个事件上绑定防抖函数 document.addEventListener("mousemove", debouncedFunction);
节流(Throttle)函数:
节流函数会在一段时间内最多执行一次,用于限制事件的触发频率。
function throttle(func, delay) { let isThrottled = false; return function (...args) { if (!isThrottled) { func.apply(this, args); isThrottled = true; setTimeout(() => { isThrottled = false; }, delay); } }; } // 用法示例 const throttledFunction = throttle(() => { console.log("节流函数被触发"); }, 1000); // 在某个事件上绑定节流函数 window.addEventListener("scroll", throttledFunction);
深拷贝(Deep Copy)和浅拷贝(Shallow Copy):
深拷贝会复制对象及其嵌套的所有子对象,而浅拷贝只会复制对象的引用。
浅拷贝示例:
const sourceObj = { a: 1, b: { c: 2 } }; const shallowCopy = Object.assign({}, sourceObj); sourceObj.b.c = 3; console.log(shallowCopy.b.c); // 输出 3,因为是浅拷贝,引用相同
引用相同
深拷贝示例:
function deepCopy(obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
let copy;
if (Array.isArray(obj)) {
copy = [];
for (let i = 0; i < obj.length; i++) {
copy[i] = deepCopy(obj[i]);
}
} else {
copy = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]);
}
}
}
return copy;
}
const sourceObj = { a: 1, b: { c: 2 } };
const deepCopiedObj = deepCopy(sourceObj);
sourceObj.b.c = 3;
console.log(deepCopiedObj.b.c); // 输出 2,因为是深拷贝,复制了对象的副本
的副本