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

本文已经过原作者 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. // Example
  9. 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. // 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. // example
  11. console.log(appendURLParams("name", "youssef")) // name=youssef
  12. /**
  13.  * Get param name from URL.
  14.  * @param {string} name
  15.  */
  16. export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name);
  17. // Example
  18. 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.   if (Math.abs(BYTES) < thresh) {
  9.     return `${BYTES} B`;
  10.   }
  11.   const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  12.   let u = -1;
  13.   const r = 10 ** 1;
  14.   do {
  15.     BYTES /= thresh;
  16.     u += 1;
  17.   } while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1);
  18.   return `${BYTES.toFixed(1)} ${units[u]}`;
  19. };
  20. // Example
  21. 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.   // loop to increment the time and push results in array
  12.   for (let i = 0; tt < 24 * 60; i += 1) {
  13.     const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
  14.     const mm = tt % 60; // getting minutes of the hour in 0-55 format
  15.     times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${
  16.       ap[Math.floor(hh / 12)]
  17.     }`; // pushing data in array in [00:00 - 12:00 AM/PM format]
  18.     tt += x;
  19.   }
  20.   return times;
  21. };
  22. // Example
  23. console.log(getTimes());
  24. /* [
  25.     "1:00 AM",
  26.     "1:15 AM",
  27.     "1:30 AM",
  28.     "1:45 AM",
  29.     "2:00 AM",
  30.     "2:15 AM",
  31.     "2:30 AM",
  32.     // ....
  33.     ]
  34. */ 

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.  * Getting values with expiry date from LocalHost that stored with `setLocalItem`.
  19.  * @param {string} key Local Storage Key
  20.  */
  21. export const getLocalItem = (key) => {
  22.   const itemStr = localStorage.getItem(key);
  23.   // if the item doesn't exist, return null
  24.   if (!itemStr) {
  25.     return null;
  26.   }
  27.   const item = JSON.parse(itemStr);
  28.   const now = new Date();
  29.   // compare the expiry time of the item with the current time
  30.   if (now.getTime() > item.expiry) {
  31.     // If the item is expired, delete the item from storage
  32.     // and return null
  33.     localStorage.removeItem(key);
  34.     return null;
  35.   }
  36.   return item.value;
  37. }; 

formatNumber()

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

我们还可以添加其他选项来获取其他数字格式,如货币、距离、权重等。

 
 
 
 
  1. export const toEGPCurrency = (num) =>
  2.   num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" });
  3. export const toUSDCurrency = (num) =>
  4.   num.toLocaleString("en-US", { style: "currency", currency: "USD" });
  5. console.log(toUSDCurrency(78899985)); // $78,899,985.00
  6. 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;
  12. }

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.   for (let i = 0; i < arr.length; i += 1) {
  4.     if (baseArr.includes(arr[i])) {
  5.       all = true;
  6.     } else {
  7.       all = false;
  8.       return all;
  9.     }
  10.   }
  11.   return all;
  12. };

你还有使用其他有用的函数吗?在评论里分享一下怎么样?

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

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

本文转载自微信公众号「大迁世界」,可以通过以下二维码关注。转载本文请联系大迁世界公众号。

网页题目:这些JavaScript函数让你的工作更加SoEasy!
本文地址:http://www.hantingmc.com/qtweb/news2/270952.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联