# 前端面试之手撕代码
# 1. 防抖函数
防抖原理:事件触发后,会在规定时间后执行,若在规定时间内再次触发,则刷新时间重新计时,直到事件执行成功
| function Debounce(fn,delay){ |
| let timer = null |
| return funtion(){ |
| timer && clearTimeOut(timer) |
| timer = setTimeOut(()=>{ |
| fn.apply(this,arguments) |
| },delay) |
| } |
| } |
| |
| function Debounce(fn, delay) { |
| const timer = null; |
| return function () { |
| timer && clearTimeout(timer); |
| timer = setTimeout(() => { |
| fn.call(this, ...arguments); |
| }, delay); |
| }; |
| } |
# 2. 节流函数
节流原理:在规定事件内事件只能被触发一次
| function throttle(fn,delay=500){ |
| let lastTime = 0 |
| return funtion(){ |
| const nowTime = Date.now() |
| if(nowTime-lastTime > delay){ |
| fn.apply(this,arguments) |
| lastTime = nowTime |
| } |
| } |
| } |
| |
| function throttle(fn, delay) { |
| let lastTime = 0; |
| return function () { |
| const nowTime = Date().now(); |
| if (nowTime - lastTime > delay) { |
| fn.call(this, ...arguments); |
| lastTime = nowTime; |
| } |
| }; |
| } |
# 3. 数组扁平化
| |
| const test = [1, 2, 3, [4, 5, [6], [7]]]; |
| function flatten(arr) { |
| let result = []; |
| for (i of arr) { |
| if (Array.isArray(i)) { |
| result = [...result, ...flatten(i)]; |
| } else { |
| result.push(i); |
| } |
| } |
| return result; |
| } |
| console.log(flatten(test)); |
| |