防抖// 函数防抖的实现 function debounce(fn, wait) { let timer null; return function() { let context this, args arguments; // 如果此时存在定时器的话则取消之前的定时器重新记时 if (timer) { clearTimeout(timer); timer null; } // 设置定时器使事件间隔指定事件后执行 timer setTimeout(() { fn.apply(context, args); }, wait); }; }节流时间戳版首段执行无尾调用// 函数节流的实现; function throttle(fn, delay) { let curTime Date.now(); return function() { let context this, args arguments, nowTime Date.now(); // 如果两次时间间隔超过了指定时间则执行函数。 if (nowTime - curTime delay) { curTime Date.now(); fn.apply(context, args); } }; }定时器版首段延迟有尾调用function throttle(fn, delay) { let timer null; return function () { const context this; const args arguments; if (!timer) { timer setTimeout(() { fn.apply(context, args); timer null; }, delay); } }; }融合版首尾调用都有function throttle(fn, delay) { // 上一次执行的时间戳 let lastTime Date.now(); // 兜底定时器标识 let timer null; return function () { const context this; const args arguments; // 当前触发时间 const now Date.now(); // 距离下一次允许执行还剩多久 const remain delay - (now - lastTime); // 场景1剩余时间 0达到间隔可以立即执行 if (remain 0) { // 如果存在等待中的兜底定时器直接清除防止重复执行 if (timer) { clearTimeout(timer); timer null; } lastTime now; fn.apply(context, args); } // 场景2时间还不足且当前没有等待的定时器则创建兜底任务 else if (!timer) { timer setTimeout(() { lastTime Date.now(); timer null; fn.apply(context, args); }, remain); } } }类型判断function getType(value) { // 单独处理两大特殊基础类型 if (value null) return null if (value undefined) return undefined // 统一调用toString const rawType Object.prototype.toString.call(value) // 截取 [object Xxx] 中间字符串 return rawType.slice(8, -1).toLowerCase() } console.log(getType(null)); // null console.log(getType(undefined)); // undefined console.log(getType(123)); // number console.log(getType(123n)); // bigint console.log(getType(aaa)); // string console.log(getType(true)); // boolean console.log(getType(Symbol())); // symbol console.log(getType([])); // array console.log(getType({})); // object console.log(getType(function(){})); // function console.log(getType(new Date())); // date console.log(getType(/\w/)); // regexp console.log(getType(new Map())); // map console.log(getType(new Set())); // setcall记得挂载函数记得解构argument记得解构argsFunction.prototype.myCall function(context) { // 1. 校验调用者必须是函数 if (typeof this ! function) { throw new TypeError(this is not a function); } // 2. 仅null/undefined替换为全局其余值原样保留 context context ?? globalThis; // 3.原始值自动装箱 context Object(context); // 4. 创建唯一临时key防止属性覆盖冲突 const tempKey Symbol(tempFunc); // 5. 挂载函数(此处this是调用call的函数) context[tempKey] this; // 6. 截取参数执行 const args [...arguments].slice(1); const result context[tempKey](...args); // 7. 删除临时方法 delete context[tempKey]; return result; };apply记得解构arguments没传参记得加function apply(ctx) { if (typeof this ! function) { throw new TypeError(type error) } let result null ctxctx??globalThis ctx Object(ctx) const tempKeySymbol(tempFn) ctx[tempKey]this if(arguments[1]){ result ctx[tempKey](...arguments[1]) }else{ resultctx[tempKey]() } delete ctx[tempKey] return result }bind解构argument参数使用concat合并解构的argument// bind 函数实现 Function.prototype.myBind function(context) { // 判断调用对象是否为函数 if (typeof this ! function) { throw new TypeError(Error); } // 获取参数 let args [...arguments].slice(1), fn this; return function Fn() { // 根据调用方式传入不同绑定值 return fn.apply( this instanceof Fn ? this : context, args.concat(...arguments) ); }; };函数柯里化function curry(fn) { // fn.length 获取函数预期形参数量 const len fn.length return function curried(...args) { // 收集参数 需要参数 → 执行 if(args.length len) { return fn(...args) } // 参数不够继续返回新函数收集 return function(...newArgs) { return curried(...args, ...newArgs) } } }浅拷贝// 浅拷贝的实现; function shallowCopy(object) { // 只拷贝对象 if (!object || typeof object ! object) return; // 根据 object 的类型判断是新建一个数组还是对象 let newObject Array.isArray(object) ? [] : {}; // 遍历 object并且判断是 object 的属性才拷贝 for (let key in object) { if (object.hasOwnProperty(key)) { newObject[key] object[key]; } } return newObject; }深拷贝// 深拷贝的实现 function deepCopy(object) { if (!object || typeof object ! object) return; let newObject Array.isArray(object) ? [] : {}; for (let key in object) { if (object.hasOwnProperty(key)) { newObject[key] typeof object[key] object ? deepCopy(object[key]) : object[key]; } } return newObject; }数组求和可多维求和const sum arr.flat(Infinity).reduce((s, v) s v, 0)数组扁平化let arr [1, [2, [3, 4]]]; function flatten(arr) { while (arr.some(item Array.isArray(item))) { arr [].concat(...arr); } return arr; } console.log(flatten(arr)); // [1, 2, 3, 45] //或者直接用flat用Promise实现图片的异步加载let imageAsync(url){ return new Promise((resolve,reject){ let img new Image(); img.src url; img.οnlοad(){ console.log(图片请求成功此处进行通用操作); resolve(image); } img.οnerrοr(err){ console.log(失败此处进行失败的通用操作); reject(err); } }) } imageAsync(url).then((){ console.log(加载成功); }).catch((error){ console.log(加载失败); })实现发布-订阅模式class EventBus { constructor() { // 存储 { 事件名: [回调函数列表] } this.events Object.create(null); } // 订阅on(事件名, 回调) on(eventName, callback) { if (!this.events[eventName]) { this.events[eventName] []; } this.events[eventName].push(callback); } // 发布/触发emit(事件名, 参数...) emit(eventName, ...args) { const cbs this.events[eventName]; if (!cbs) return; // 循环执行所有订阅回调传入参数 cbs.forEach(fn fn(...args)); } // 取消订阅off(事件名, 指定回调) off(eventName, callback) { const cbs this.events[eventName]; if (!cbs) return; this.events[eventName] cbs.filter(item item ! callback); } // 一次性订阅once触发后自动解绑 once(eventName, callback) { const wrapper (...args) { callback(...args); this.off(eventName, wrapper); }; this.on(eventName, wrapper); } }
手撕小汇总
发布时间:2026/7/17 20:14:05
防抖// 函数防抖的实现 function debounce(fn, wait) { let timer null; return function() { let context this, args arguments; // 如果此时存在定时器的话则取消之前的定时器重新记时 if (timer) { clearTimeout(timer); timer null; } // 设置定时器使事件间隔指定事件后执行 timer setTimeout(() { fn.apply(context, args); }, wait); }; }节流时间戳版首段执行无尾调用// 函数节流的实现; function throttle(fn, delay) { let curTime Date.now(); return function() { let context this, args arguments, nowTime Date.now(); // 如果两次时间间隔超过了指定时间则执行函数。 if (nowTime - curTime delay) { curTime Date.now(); fn.apply(context, args); } }; }定时器版首段延迟有尾调用function throttle(fn, delay) { let timer null; return function () { const context this; const args arguments; if (!timer) { timer setTimeout(() { fn.apply(context, args); timer null; }, delay); } }; }融合版首尾调用都有function throttle(fn, delay) { // 上一次执行的时间戳 let lastTime Date.now(); // 兜底定时器标识 let timer null; return function () { const context this; const args arguments; // 当前触发时间 const now Date.now(); // 距离下一次允许执行还剩多久 const remain delay - (now - lastTime); // 场景1剩余时间 0达到间隔可以立即执行 if (remain 0) { // 如果存在等待中的兜底定时器直接清除防止重复执行 if (timer) { clearTimeout(timer); timer null; } lastTime now; fn.apply(context, args); } // 场景2时间还不足且当前没有等待的定时器则创建兜底任务 else if (!timer) { timer setTimeout(() { lastTime Date.now(); timer null; fn.apply(context, args); }, remain); } } }类型判断function getType(value) { // 单独处理两大特殊基础类型 if (value null) return null if (value undefined) return undefined // 统一调用toString const rawType Object.prototype.toString.call(value) // 截取 [object Xxx] 中间字符串 return rawType.slice(8, -1).toLowerCase() } console.log(getType(null)); // null console.log(getType(undefined)); // undefined console.log(getType(123)); // number console.log(getType(123n)); // bigint console.log(getType(aaa)); // string console.log(getType(true)); // boolean console.log(getType(Symbol())); // symbol console.log(getType([])); // array console.log(getType({})); // object console.log(getType(function(){})); // function console.log(getType(new Date())); // date console.log(getType(/\w/)); // regexp console.log(getType(new Map())); // map console.log(getType(new Set())); // setcall记得挂载函数记得解构argument记得解构argsFunction.prototype.myCall function(context) { // 1. 校验调用者必须是函数 if (typeof this ! function) { throw new TypeError(this is not a function); } // 2. 仅null/undefined替换为全局其余值原样保留 context context ?? globalThis; // 3.原始值自动装箱 context Object(context); // 4. 创建唯一临时key防止属性覆盖冲突 const tempKey Symbol(tempFunc); // 5. 挂载函数(此处this是调用call的函数) context[tempKey] this; // 6. 截取参数执行 const args [...arguments].slice(1); const result context[tempKey](...args); // 7. 删除临时方法 delete context[tempKey]; return result; };apply记得解构arguments没传参记得加function apply(ctx) { if (typeof this ! function) { throw new TypeError(type error) } let result null ctxctx??globalThis ctx Object(ctx) const tempKeySymbol(tempFn) ctx[tempKey]this if(arguments[1]){ result ctx[tempKey](...arguments[1]) }else{ resultctx[tempKey]() } delete ctx[tempKey] return result }bind解构argument参数使用concat合并解构的argument// bind 函数实现 Function.prototype.myBind function(context) { // 判断调用对象是否为函数 if (typeof this ! function) { throw new TypeError(Error); } // 获取参数 let args [...arguments].slice(1), fn this; return function Fn() { // 根据调用方式传入不同绑定值 return fn.apply( this instanceof Fn ? this : context, args.concat(...arguments) ); }; };函数柯里化function curry(fn) { // fn.length 获取函数预期形参数量 const len fn.length return function curried(...args) { // 收集参数 需要参数 → 执行 if(args.length len) { return fn(...args) } // 参数不够继续返回新函数收集 return function(...newArgs) { return curried(...args, ...newArgs) } } }浅拷贝// 浅拷贝的实现; function shallowCopy(object) { // 只拷贝对象 if (!object || typeof object ! object) return; // 根据 object 的类型判断是新建一个数组还是对象 let newObject Array.isArray(object) ? [] : {}; // 遍历 object并且判断是 object 的属性才拷贝 for (let key in object) { if (object.hasOwnProperty(key)) { newObject[key] object[key]; } } return newObject; }深拷贝// 深拷贝的实现 function deepCopy(object) { if (!object || typeof object ! object) return; let newObject Array.isArray(object) ? [] : {}; for (let key in object) { if (object.hasOwnProperty(key)) { newObject[key] typeof object[key] object ? deepCopy(object[key]) : object[key]; } } return newObject; }数组求和可多维求和const sum arr.flat(Infinity).reduce((s, v) s v, 0)数组扁平化let arr [1, [2, [3, 4]]]; function flatten(arr) { while (arr.some(item Array.isArray(item))) { arr [].concat(...arr); } return arr; } console.log(flatten(arr)); // [1, 2, 3, 45] //或者直接用flat用Promise实现图片的异步加载let imageAsync(url){ return new Promise((resolve,reject){ let img new Image(); img.src url; img.οnlοad(){ console.log(图片请求成功此处进行通用操作); resolve(image); } img.οnerrοr(err){ console.log(失败此处进行失败的通用操作); reject(err); } }) } imageAsync(url).then((){ console.log(加载成功); }).catch((error){ console.log(加载失败); })实现发布-订阅模式class EventBus { constructor() { // 存储 { 事件名: [回调函数列表] } this.events Object.create(null); } // 订阅on(事件名, 回调) on(eventName, callback) { if (!this.events[eventName]) { this.events[eventName] []; } this.events[eventName].push(callback); } // 发布/触发emit(事件名, 参数...) emit(eventName, ...args) { const cbs this.events[eventName]; if (!cbs) return; // 循环执行所有订阅回调传入参数 cbs.forEach(fn fn(...args)); } // 取消订阅off(事件名, 指定回调) off(eventName, callback) { const cbs this.events[eventName]; if (!cbs) return; this.events[eventName] cbs.filter(item item ! callback); } // 一次性订阅once触发后自动解绑 once(eventName, callback) { const wrapper (...args) { callback(...args); this.off(eventName, wrapper); }; this.on(eventName, wrapper); } }