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

這些 JavaScript函數讓你的工作更加 So Easy!

開發(fā) 前端
你是否有一個DDL,它每n分鐘顯示一天的時間?用這個函數。

[[384757]]

本文已經過原作者 YoussefZidan 授權翻譯。

randomNumber()

獲取指定區(qū)間的隨機數。

  1. ** 
  2.  * 在最小值和最大值之間生成隨機整數。 
  3.  * @param {number} min Min number 
  4.  * @param {number} max Max Number 
  5.  */ 
  6. export const randomNumber = (min = 0, max = 1000) => 
  7.   Math.ceil(min + Math.random() * (max - min)); 
  8.  
  9. // Example 
  10. console.log(randomNumber()); // 97  

capitalize()

將字符串的第一個字母變?yōu)榇髮憽?/p>

  1. /** 
  2.  * Capitalize Strings. 
  3.  * @param {string} s String that will be Capitalized 
  4.  */ 
  5. export const capitalize = (s) => { 
  6.   if (typeof s !== "string"return ""
  7.   return s.charAt(0).toUpperCase() + s.slice(1); 
  8.  
  9. // Example 
  10. console.log(capitalize("cat")); // Cat 

truncate();

這對于長字符串很有用,特別是在表內部。

  1. /** 
  2.  * 截斷字符串.... 
  3.  * @param {string} 要截斷的文本字符串 
  4.  * @param {number} 截斷的長度 
  5.  */ 
  6. export const truncate = (text, num = 10) => { 
  7.   if (text.length > num) { 
  8.     return `${text.substring(0, num - 3)}...` 
  9.   } 
  10.   return text; 
  11.  
  12. // Example 
  13. console.log(truncate("this is some long string to be truncated"));   
  14.  
  15. // this is...  

toTop();

滾到到底部,可以通過 behavior 屬性指定滾動速度狀態(tài)。

  1. /** 
  2.  * Scroll to top 
  3.  */ 
  4. export const toTop = () => { 
  5.   window.scroll({ top: 0, left: 0, behavior: "smooth" }); 
  6. };  

softDeepClone()

這個方法是經常被用到的,因為有了它,我們可以深度克隆嵌套數組或對象。

不過,這個函數不能與new Date()、NaN、undefined、function、Number、Infinity等數據類型一起工作。

你想深度克隆上述數據類型,可以使用 lodash 中的 cloneDeep() 函數。

  1. /** 
  2.  * Deep cloning inputs 
  3.  * @param {any} input Input 
  4.  */ 
  5. export const softDeepClone= (input) => JSON.parse(JSON.stringify(input)); 

appendURLParams() & getURLParams()

快速添加和獲取查詢字符串的方法,我通常使用它們將分頁元數據存儲到url。

  1. /** 
  2.  * Appen query string and return the value in a query string format. 
  3.  * @param {string} key 
  4.  * @param {string} value 
  5.  */ 
  6. export const appendURLParams = (key, value) => { 
  7.   const searchParams = new URLSearchParams(window.location.search).set(key, value); 
  8.   return searchParams.toString(); 
  9. }; 
  10.  
  11. // example 
  12. console.log(appendURLParams("name""youssef")) // name=youssef 
  13.  
  14. /** 
  15.  * Get param name from URL. 
  16.  * @param {string} name 
  17.  */ 
  18. export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name); 
  19.  
  20. // Example 
  21. console.log(getURLParams(id)) // 5 

getInnerHTML()

每當服務器返回一串HTML元素時,我都會使用它。

  1. /** 
  2.  * 獲取HTML字符串的內部Text 
  3.  * @param {string} str A string of HTML 
  4.  */ 
  5. export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, ""); 

scrollToHide()

上滾動以顯示HTML元素,向下滾動以將其隱藏。

  1. /** 
  2.  * 下滾動時隱藏HTML元素。 
  3.  * @param {string} 元素的 id 
  4.  * @param {string} distance in px ex: "100px" 
  5.  */ 
  6. export const scrollToHide = (id, distance) => { 
  7.   let prevScrollpos = window.pageYOffset; 
  8.   window.onscroll = () => { 
  9.     const currentScrollPos = window.pageYOffset; 
  10.     if (prevScrollpos > currentScrollPos) { 
  11.       document.getElementById(id).style.transform = `translateY(${distance})`; 
  12.     } else { 
  13.       document.getElementById(id).style.transform = `translateY(-${distance})`; 
  14.     } 
  15.     prevScrollpos = currentScrollPos; 
  16.   }; 
  17. }; 

humanFileSize ()

傳入字節(jié)為單位的文件,返回我們日常所熟悉的單位。

  1. /** 
  2.  * Converting Bytes to Readable Human File Sizes. 
  3.  * @param {number} bytes Bytes in Number 
  4.  */ 
  5. export const humanFileSize = (bytes) => { 
  6.   let BYTES = bytes; 
  7.   const thresh = 1024; 
  8.  
  9.   if (Math.abs(BYTES) < thresh) { 
  10.     return `${BYTES} B`; 
  11.   } 
  12.  
  13.   const units = ["kB""MB""GB""TB""PB""EB""ZB""YB"]; 
  14.  
  15.   let u = -1; 
  16.   const r = 10 ** 1; 
  17.  
  18.   do { 
  19.     BYTES /= thresh; 
  20.     u += 1; 
  21.   } while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1); 
  22.  
  23.   return `${BYTES.toFixed(1)} ${units[u]}`; 
  24. }; 
  25.  
  26. // Example 
  27. console.log(humanFileSize(456465465)); // 456.5 MB 

getTimes()

你是否有一個DDL,它每n分鐘顯示一天的時間?用這個函數。

  1. /** 
  2.  * Getting an Array of Times + "AM" or "PM"
  3.  * @param {number} minutesInterval 
  4.  * @param {number} startTime  
  5.  */ 
  6. export const getTimes = (minutesInterval = 15, startTime = 60) => { 
  7.   const times = []; // time array 
  8.   const x = minutesInterval; // minutes interval 
  9.   let tt = startTime; // start time 
  10.   const ap = ["AM""PM"]; // AM-PM 
  11.  
  12.   // loop to increment the time and push results in array 
  13.   for (let i = 0; tt < 24 * 60; i += 1) { 
  14.     const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format 
  15.     const mm = tt % 60; // getting minutes of the hour in 0-55 format 
  16.     times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${ 
  17.       ap[Math.floor(hh / 12)] 
  18.     }`; // pushing data in array in [00:00 - 12:00 AM/PM format] 
  19.     tt += x; 
  20.   } 
  21.   return times; 
  22. }; 
  23.  
  24. // Example 
  25. console.log(getTimes()); 
  26. /* [ 
  27.     "1:00 AM"
  28.     "1:15 AM"
  29.     "1:30 AM"
  30.     "1:45 AM"
  31.     "2:00 AM"
  32.     "2:15 AM"
  33.     "2:30 AM"
  34.     // .... 
  35.     ] 
  36. */  

setLocalItem() & getLocalItem()

讓 LocalStorage 具有過期時間。

  1. /** 
  2.  * Caching values with expiry date to the LocalHost. 
  3.  * @param {string} key Local Storage Key 
  4.  * @param {any} value Local Storage Value 
  5.  * @param {number} ttl Time to live (Expiry Date in MS) 
  6.  */ 
  7. export const setLocalItem = (key, value, ttl = duration.month) => { 
  8.   const now = new Date(); 
  9.   // `item` is an object which contains the original value 
  10.   // as well as the time when it's supposed to expire 
  11.   const item = { 
  12.     value, 
  13.     expiry: now.getTime() + ttl, 
  14.   }; 
  15.   localStorage.setItem(key, JSON.stringify(item)); 
  16. }; 
  17.  
  18. /** 
  19.  * Getting values with expiry date from LocalHost that stored with `setLocalItem`. 
  20.  * @param {string} key Local Storage Key 
  21.  */ 
  22. export const getLocalItem = (key) => { 
  23.   const itemStr = localStorage.getItem(key); 
  24.   // if the item doesn't exist, return null 
  25.   if (!itemStr) { 
  26.     return null
  27.   } 
  28.   const item = JSON.parse(itemStr); 
  29.   const now = new Date(); 
  30.   // compare the expiry time of the item with the current time 
  31.   if (now.getTime() > item.expiry) { 
  32.     // If the item is expired, delete the item from storage 
  33.     // and return null 
  34.     localStorage.removeItem(key); 
  35.     return null
  36.   } 
  37.   return item.value; 
  38. };  

formatNumber()

  1. /** 
  2.  * Format numbers with separators. 
  3.  * @param {number} num 
  4.  */ 
  5. export const formatNumber = (num) => num.toLocaleString(); 
  6.  
  7. // Example 
  8. console.log(formatNumber(78899985)); // 78,899,985 

我們還可以添加其他選項來獲取其他數字格式,如貨幣、距離、權重等。

  1. export const toEGPCurrency = (num) => 
  2.   num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" }); 
  3.  
  4. export const toUSDCurrency = (num) => 
  5.   num.toLocaleString("en-US", { style: "currency", currency: "USD" }); 
  6.  
  7. console.log(toUSDCurrency(78899985)); // $78,899,985.00 
  8. console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م. 

toFormData()

每當我需要向服務器發(fā)送文件時,我就使用這個函數。

  1. /** 
  2.  * Convert Objects to Form Data Format. 
  3.  * @param {object} obj 
  4.  */ 
  5. export const toFormData = (obj) => { 
  6.   const formBody = new FormData(); 
  7.   Object.keys(obj).forEach((key) => { 
  8.     formBody.append(key, obj[key]) 
  9.   }) 
  10.    
  11.   return formBody; 

getScreenWidth()

獲取一個表示屏幕寬度的字符串。

  1. /** 
  2.  * Detect screen width and returns a string representing the width of the screen. 
  3.  */ 
  4. export const getScreenWidth = () => { 
  5.   const screenWidth = window.screen.width; 
  6.   if (screenWidth <= 425) return "mobile"
  7.   if (screenWidth <= 768) return "tablet"
  8.   if (screenWidth <= 1024) return "laptopSm"
  9.   if (screenWidth <= 1440) return "laptopLg"
  10.   if (screenWidth <= 2560) return "HD"
  11.   return screenWidth; 
  12. };  

檢查數組中的每個元素是否存在于另一個數組中。

  1. export const containsAll = (baseArr, arr) => { 
  2.   let all = false
  3.  
  4.   for (let i = 0; i < arr.length; i += 1) { 
  5.     if (baseArr.includes(arr[i])) { 
  6.       all = true
  7.     } else { 
  8.       all = false
  9.       return all
  10.     } 
  11.   } 
  12.  
  13.   return all
  14. }; 

你還有使用其他有用的函數嗎?在評論里分享一下怎么樣?

完~,我是小智,我要去刷碗去了。

作者:YoussefZidan 譯者:前端小智 來源:dev原文:https://dev.to/youssefzidan/javascript-functions-that-will-make-your-life-much-easier-1imh

本文轉載自微信公眾號「大遷世界」,可以通過以下二維碼關注。轉載本文請聯系大遷世界公眾號。

 

責任編輯:武曉燕 來源: 大遷世界
相關推薦

2022-03-18 08:00:48

Chrome工具前端

2015-10-23 15:00:30

數據中心求職

2020-08-12 18:11:02

戴爾

2020-07-06 14:18:25

Linux 系統 數據

2025-03-11 08:30:00

Pythonretrying代碼

2010-09-09 16:39:24

2023-07-03 07:55:25

2021-07-01 10:03:55

Distroless容器安全

2024-08-02 10:23:20

2023-07-04 13:35:00

Monorepos工具管理

2018-09-05 21:07:06

數據管理

2021-09-11 22:51:38

Windows 10Windows微軟

2019-08-28 09:28:07

SSHOpenSSH運維

2022-11-07 16:25:07

JavaScript技巧

2012-09-07 09:41:15

Win 8關機

2020-11-23 09:21:09

開源項目

2022-09-19 15:02:24

C語言

2023-12-08 13:47:29

AI工具ChatGPT

2013-08-28 10:20:56

2018-09-18 23:29:43

小程序云服務
點贊
收藏

51CTO技術棧公眾號