自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

十個(gè)常見的前端手寫功能,你全都會嗎?

開發(fā) 前端
萬丈高樓平地起,地基打的牢,才能永遠(yuǎn)立于不敗之地。今天給大家?guī)淼氖?0個(gè)常見的 JavaScript 手寫功能,重要的地方已添加注釋。有的是借鑒別人的,有的是自己寫的,如有不正確的地方,歡迎多多指正。

萬丈高樓平地起,地基打的牢,才能永遠(yuǎn)立于不敗之地。今天給大家?guī)淼氖?0個(gè)常見的 JavaScript 手寫功能,重要的地方已添加注釋。有的是借鑒別人的,有的是自己寫的,如有不正確的地方,歡迎多多指正。

[[440884]]

1、防抖

 

  1. function debounce(fn, delay) { 
  2.   let timer 
  3.   return function (...args) { 
  4.     if (timer) { 
  5.       clearTimeout(timer) 
  6.     } 
  7.     timer = setTimeout(() => { 
  8.       fn.apply(this, args) 
  9.     }, delay) 
  10.   } 
  11.  
  12. // 測試 
  13. function task() { 
  14.   console.log('run task'
  15. const debounceTask = debounce(task, 1000) 
  16. window.addEventListener('scroll', debounceTask) 

 

2、節(jié)流

 

  1. function throttle(fn, delay) { 
  2.   let last = 0 // 上次觸發(fā)時(shí)間 
  3.   return (...args) => { 
  4.     const now = Date.now() 
  5.     if (now - last > delay) { 
  6.       last = now 
  7.       fn.apply(this, args) 
  8.     } 
  9.   } 
  10.  
  11. // 測試 
  12. function task() { 
  13.   console.log('run task'
  14. const throttleTask = throttle(task, 1000) 
  15. window.addEventListener('scroll', throttleTask) 

 

3、深拷貝

 

  1. function deepClone(obj, cache = new WeakMap()) { 
  2.   if (typeof obj !== 'object'return obj // 普通類型,直接返回 
  3.   if (obj === nullreturn obj 
  4.   if (cache.get(obj)) return cache.get(obj) // 防止循環(huán)引用,程序進(jìn)入死循環(huán) 
  5.   if (obj instanceof Datereturn new Date(obj) 
  6.   if (obj instanceof RegExp) return new RegExp(obj) 
  7.    
  8.   // 找到所屬原型上的constructor,所屬原型上的constructor指向當(dāng)前對象的構(gòu)造函數(shù) 
  9.   let cloneObj = new obj.constructor() 
  10.   cache.set(obj, cloneObj) // 緩存拷貝的對象,用于處理循環(huán)引用的情況 
  11.   for (let key in obj) { 
  12.     if (obj.hasOwnProperty(key)) { 
  13.       cloneObj[key] = deepClone(obj[key], cache) // 遞歸拷貝 
  14.     } 
  15.   } 
  16.   return cloneObj 
  17.  
  18. // 測試 
  19. const obj = { name'Jack', address: { x: 100, y: 200 } } 
  20. obj.a = obj // 循環(huán)引用 
  21. const newObj = deepClone(obj) 
  22. console.log(newObj.address === obj.address) // false 

 

4、實(shí)現(xiàn) Promise

 

  1. class MyPromise { 
  2.   constructor(executor) { // executor執(zhí)行器 
  3.     this.status = 'pending' // 等待狀態(tài) 
  4.     this.value = null // 成功或失敗的參數(shù) 
  5.     this.fulfilledCallbacks = [] // 成功的函數(shù)隊(duì)列 
  6.     this.rejectedCallbacks = [] // 失敗的函數(shù)隊(duì)列 
  7.     const that = this 
  8.     function resolve(value) { // 成功的方法 
  9.       if (that.status === 'pending') { 
  10.         that.status = 'resolved' 
  11.         that.value = value 
  12.         that.fulfilledCallbacks.forEach(myFn => myFn(that.value)) //執(zhí)行回調(diào)方法 
  13.       } 
  14.     } 
  15.     function reject(value) { //失敗的方法 
  16.       if (that.status === 'pending') { 
  17.         that.status = 'rejected' 
  18.         that.value = value 
  19.         that.rejectedCallbacks.forEach(myFn => myFn(that.value)) //執(zhí)行回調(diào)方法 
  20.       } 
  21.     } 
  22.     try { 
  23.       executor(resolve, reject) 
  24.     } catch (err) { 
  25.       reject(err) 
  26.     } 
  27.   } 
  28.   then(onFulfilled, onRejected) { 
  29.     if (this.status === 'pending') { 
  30.       // 等待狀態(tài),添加回調(diào)函數(shù)到成功的函數(shù)隊(duì)列 
  31.       this.fulfilledCallbacks.push(() => { 
  32.         onFulfilled(this.value) 
  33.       }) 
  34.       // 等待狀態(tài),添加回調(diào)函數(shù)到失敗的函數(shù)隊(duì)列 
  35.       this.rejectedCallbacks.push(() => { 
  36.         onRejected(this.value) 
  37.       }) 
  38.     } 
  39.     if (this.status === 'resolved') { // 支持同步調(diào)用 
  40.       console.log('this', this) 
  41.       onFulfilled(this.value) 
  42.     } 
  43.     if (this.status === 'rejected') { // 支持同步調(diào)用 
  44.       onRejected(this.value) 
  45.     } 
  46.   } 
  47.  
  48. // 測試 
  49. function fn() { 
  50.   return new MyPromise((resolve, reject) => { 
  51.     setTimeout(() => { 
  52.       if(Math.random() > 0.6) { 
  53.         resolve(1) 
  54.       } else { 
  55.         reject(2) 
  56.       } 
  57.     }, 1000) 
  58.   }) 
  59. fn().then
  60.   res => { 
  61.     console.log('res', res) // res 1 
  62.   }, 
  63.   err => { 
  64.     console.log('err', err) // err 2 
  65.   }) 

 

5、異步控制并發(fā)數(shù)

 

  1. function limitRequest(urls = [], limit = 3) { 
  2.   return new Promise((resolve, reject) => { 
  3.     const len = urls.length 
  4.     let count = 0 // 當(dāng)前進(jìn)行到第幾個(gè)任務(wù) 
  5.  
  6.     const start = async () => { 
  7.       const url = urls.shift() // 從數(shù)組中拿取第一個(gè)任務(wù) 
  8.       if (url) { 
  9.         try { 
  10.           await axios.post(url) 
  11.           if (count == len - 1) { 
  12.             // 最后一個(gè)任務(wù)成功 
  13.             resolve() 
  14.           } else { 
  15.             count++ 
  16.             // 成功,啟動下一個(gè)任務(wù) 
  17.             start() 
  18.           } 
  19.         } catch (e) { 
  20.           if (count == len - 1) { 
  21.             // 最后一個(gè)任務(wù)失敗 
  22.             resolve() 
  23.           } else { 
  24.             count++ 
  25.             // 失敗,啟動下一個(gè)任務(wù) 
  26.             start() 
  27.           } 
  28.         } 
  29.       } 
  30.     } 
  31.  
  32.     // 啟動limit個(gè)任務(wù) 
  33.     while (limit > 0) { 
  34.       start() 
  35.       limit -= 1 
  36.     } 
  37.   }) 
  38.  
  39. // 測試 
  40. limitRequest(['http://xxa''http://xxb''http://xxc''http://xxd''http://xxe']) 

 

6、ES5繼承(寄生組合繼承)

 

  1. function Parent(name) { 
  2.   this.name = name 
  3. Parent.prototype.eat = function () { 
  4.   console.log(this.name + ' is eating'
  5.  
  6. function Child(name, age) { 
  7.   Parent.call(this, name
  8.   this.age = age 
  9. Child.prototype = Object.create(Parent.prototype) 
  10. Child.prototype.contructor = Child 
  11. Child.prototype.study = function () { 
  12.   console.log(this.name + ' is studying'
  13.  
  14. // 測試 
  15. let child = new Child('xiaoming', 16) 
  16. console.log(child.name) // xiaoming 
  17. child.eat() // xiaoming is eating 
  18. child.study() // xiaoming is studying 

 

7、數(shù)組排序

sort 排序

 

  1. // 對數(shù)字進(jìn)行排序,簡寫 
  2. const arr = [3, 2, 4, 1, 5] 
  3. arr.sort((a, b) => a - b) 
  4. console.log(arr) // [1, 2, 3, 4, 5] 
  5.  
  6. // 對字母進(jìn)行排序,簡寫 
  7. const arr = ['b''c''a''e''d'
  8. arr.sort() 
  9. console.log(arr) // ['a''b''c''d''e' 

 

冒泡排序

 

  1. function bubbleSort(arr) { 
  2.   let len = arr.length 
  3.   for (let i = 0; i < len - 1; i++) { 
  4.     // 從第一個(gè)元素開始,比較相鄰的兩個(gè)元素,前者大就交換位置 
  5.     for (let j = 0; j < len - 1 - i; j++) { 
  6.       if (arr[j] > arr[j + 1]) { 
  7.         let num = arr[j] 
  8.         arr[j] = arr[j + 1] 
  9.         arr[j + 1] = num 
  10.       } 
  11.     } 
  12.     // 每次遍歷結(jié)束,都能找到一個(gè)最大值,放在數(shù)組最后 
  13.   } 
  14.   return arr 
  15.  
  16. //測試 
  17. console.log(bubbleSort([2, 3, 1, 5, 4])) // [1, 2, 3, 4, 5] 

 

8、數(shù)組去重

Set 去重

 

  1. cosnt newArr = [...new Set(arr)]  

 

Array.from 去重

 

  1. const newArr = Array.from(new Set(arr)) 

indexOf 去重

 

  1. function resetArr(arr) { 
  2.   let res = [] 
  3.   arr.forEach(item => { 
  4.     if (res.indexOf(item) === -1) { 
  5.       res.push(item) 
  6.     } 
  7.   }) 
  8.   return res 
  9.  
  10. // 測試 
  11. const arr = [1, 1, 2, 3, 3] 
  12. console.log(resetArr(arr)) // [1, 2, 3] 

 

9、獲取 url 參數(shù)

URLSearchParams 方法

 

  1. // 創(chuàng)建一個(gè)URLSearchParams實(shí)例 
  2. const urlSearchParams = new URLSearchParams(window.location.search); 
  3. // 把鍵值對列表轉(zhuǎn)換為一個(gè)對象 
  4. const params = Object.fromEntries(urlSearchParams.entries()); 

 

split 方法

 

  1. function getParams(url) { 
  2.   const res = {} 
  3.   if (url.includes('?')) { 
  4.     const str = url.split('?')[1] 
  5.     const arr = str.split('&'
  6.     arr.forEach(item => { 
  7.       const key = item.split('=')[0] 
  8.       const val = item.split('=')[1] 
  9.       res[key] = decodeURIComponent(val) // 解碼 
  10.     }) 
  11.   } 
  12.   return res 
  13.  
  14. // 測試 
  15. const user = getParams('http://www.baidu.com?user=%E9%98%BF%E9%A3%9E&age=16'
  16. console.log(user) // { user'阿飛', age: '16' } 

 

10、事件總線 | 發(fā)布訂閱模式

 

  1. class EventEmitter { 
  2.   constructor() { 
  3.     this.cache = {} 
  4.   } 
  5.  
  6.   on(name, fn) { 
  7.     if (this.cache[name]) { 
  8.       this.cache[name].push(fn) 
  9.     } else { 
  10.       this.cache[name] = [fn] 
  11.     } 
  12.   } 
  13.  
  14.   off(name, fn) { 
  15.     const tasks = this.cache[name
  16.     if (tasks) { 
  17.       const index = tasks.findIndex((f) => f === fn || f.callback === fn) 
  18.       if (index >= 0) { 
  19.         tasks.splice(index, 1) 
  20.       } 
  21.     } 
  22.   } 
  23.  
  24.   emit(name, once = false) { 
  25.     if (this.cache[name]) { 
  26.       // 創(chuàng)建副本,如果回調(diào)函數(shù)內(nèi)繼續(xù)注冊相同事件,會造成死循環(huán) 
  27.       const tasks = this.cache[name].slice() 
  28.       for (let fn of tasks) { 
  29.         fn(); 
  30.       } 
  31.       if (once) { 
  32.         delete this.cache[name
  33.       } 
  34.     } 
  35.   } 
  36.  
  37. // 測試 
  38. const eventBus = new EventEmitter() 
  39. const task1 = () => { console.log('task1'); } 
  40. const task2 = () => { console.log('task2'); } 
  41.  
  42. eventBus.on('task', task1) 
  43. eventBus.on('task', task2) 
  44. eventBus.off('task', task1) 
  45. setTimeout(() => { 
  46.   eventBus.emit('task') // task2 
  47. }, 1000) 

 

 

以上就是工作或求職中最常見的手寫功能,你是不是全都掌握了呢

 

責(zé)任編輯:華軒 來源: 今日頭條
相關(guān)推薦

2023-07-14 11:36:09

GPT-4社交

2023-12-15 10:42:05

2025-01-17 11:38:10

2022-11-25 14:55:43

JavaScriptweb應(yīng)用程序

2023-05-28 22:48:29

程序員編程

2022-07-31 23:54:24

Linux操作系統(tǒng)

2022-06-06 16:40:20

工作流程效率管理

2022-07-31 23:53:37

Linux操作系統(tǒng)設(shè)備

2023-12-22 16:48:00

Kubernetes容器集群

2022-01-05 11:40:36

Go特性語言

2019-04-01 06:37:12

R語言數(shù)據(jù)分析數(shù)據(jù)

2010-03-04 16:09:09

2020-03-25 10:27:59

Python語言

2023-12-27 14:12:40

JavaScrip技巧

2023-07-14 14:25:00

Python語言錯(cuò)誤

2025-03-18 14:27:35

2024-09-24 07:57:55

SQL錯(cuò)誤??EXPLAIN?

2022-05-16 07:48:54

Python操作類型

2023-07-14 10:53:00

開源前端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號