这些 JavaScript函数让你的工作更加 So Easy!

开发 前端
你是否有一个DDL,它每n分钟显示一天的时间?用这个函数。

[[384757]]

本文已经过原作者 YoussefZidan 授权翻译。

randomNumber()

获取指定区间的随机数。

  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()

将字符串的第一个字母变为大写。

  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 属性指定滚动速度状态。

  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 ()

传入字节为单位的文件,返回我们日常所熟悉的单位。

  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()

每当我需要向服务器发送文件时,我就使用这个函数。

  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 系统 数据

2023-07-03 07:55:25

2021-07-01 10:03:55

Distroless容器安全

2010-09-09 16:39:24

2018-09-05 21:07:06

数据管理

2012-09-07 09:41:15

Win 8关机

2023-07-04 13:35:00

Monorepos工具管理

2019-08-28 09:28:07

SSHOpenSSH运维

2018-09-18 23:29:43

小程序云服务

2022-09-19 15:02:24

C语言

2022-11-07 16:25:07

JavaScript技巧

2020-11-23 09:21:09

开源项目

2021-09-11 22:51:38

Windows 10Windows微软

2019-12-23 10:51:40

Python车票抢票

2022-11-26 00:00:02

2023-12-08 13:47:29

AI工具ChatGPT

2013-08-28 10:20:56

点赞
收藏

51CTO技术栈公众号