函数库

45 阅读1分钟

函数防抖: function debounce(func, wait) { // 设置变量,记录 setTimeout 得到的 id var timerId = null; return function (...args) { if (timerId) { // 如果有值,说明目前正在等待中,清除它 clearTimeout(timerId); } // 重新开始计时 timerId = setTimeout(() => { func(...args); }, wait); } } 函数节流: function throttle(func, wait) { var timeId return function (...args) { //args = arguments; // 如果 timeout 有值,说明上一次的执行间隔时间还没过 if (!timeId) { // 进入此 if 说明时间间隔已经过了 // 先执行一次要执行的函数 func(...args) // 然后重新设置时间间隔 timeId = setTimeout(function () { timeId = null; }, wait); } } } 深度拷贝: function deepCopy(oldObj, newobj) { for (var key in oldObj) { var item = oldObj[key]; // 判断是否是对象 if (item instanceof Object) { if (item instanceof Function) { newobj[key] = oldObj[key]; } else { newobj[key] = {}; //定义一个空的对象来接收拷贝的内容 deepCopy(item, newobj[key]); //递归调用 } // 判断是否是数组 } else if (item instanceof Array) { newobj[key] = []; //定义一个空的数组来接收拷贝的内容 deepCopy(item, newobj[key]); //递归调用 } else { newobj[key] = oldObj[key]; } } } 柯里化函数: function curry() { var fn = arguments[0]; // 获取要执行的函数 var args = [].slice.call(arguments, 1); // 获取传递的参数,构成一个参数数组 // 如果传递的参数已经等于执行函数所需的参数数量 if (args.length === fn.length) { return fn.apply(this, args) } // 参数不够向外界返回的函数 function _curry(){ // 推入之前判断 // 将新接收到的参数推入到参数数组中 args.push(...arguments); if(args.length === fn.length){ return fn.apply(this, args) } return _curry; } return _curry; }