作者: YoussefZidan
译者:前端小智
来源:dev
点赞再看,养成习惯
本文
GitHubhttps://github.com/qq44924588... 上已经收录,更多往期高赞文章的分类,也整理了很多我的文档,和教程资料。欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。
最近开源了一个 Vue 组件,还不够完善,欢迎大家来一起完善它,也希望大家能给个 star 支持一下,谢谢各位了。
github 地址:https://github.com/qq44924588...
在本文中,分享一些我几乎在每个项目中都会用到的一些函数。
randomNumber()
获取指定区间的随机数。
1** 2 * 在最小值和最大值之间生成随机整数。 3 * @param {number} min Min number 4 * @param {number} max Max Number 5 */ 6export const randomNumber = (min = 0, max = 1000) => 7 Math.ceil(min + Math.random() * (max - min)); 8 9// Example 10console.log(randomNumber()); // 97
capitalize()
将字符串的第一个字母变为大写。
1/** 2 * Capitalize Strings. 3 * @param {string} s String that will be Capitalized 4 */ 5export const capitalize = (s) => { 6 if (typeof s !== "string") return ""; 7 return s.charAt(0).toUpperCase() + s.slice(1); 8} 9 10// Example 11console.log(capitalize("cat")); // Cat
truncate();
这对于长字符串很有用,特别是在表内部。
1/** 2 * 截断字符串.... 3 * @param {string} 要截断的文本字符串 4 * @param {number} 截断的长度 5 */ 6export const truncate = (text, num = 10) => { 7 if (text.length > num) { 8 return `${text.substring(0, num - 3)}...` 9 } 10 return text; 11} 12 13// Example 14console.log(truncate("this is some long string to be truncated")); 15 16// this is...
toTop();
滚到到底部,可以通过 behavior 属性指定滚动速度状态。
1/** 2 * Scroll to top 3 */ 4export 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 */ 5export 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 */ 6export const appendURLParams = (key, value) => { 7 const searchParams = new URLSearchParams(window.location.search).set(key, value); 8 return searchParams.toString(); 9}; 10 11// example 12console.log(appendURLParams("name", "youssef")) // name=youssef 13 14/** 15 * Get param name from URL. 16 * @param {string} name 17 */ 18export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name); 19 20// Example 21console.log(getURLParams(id)) // 5
getInnerHTML()
每当服务器返回一串HTML元素时,我都会使用它。
1/** 2 * 获取HTML字符串的内部Text 3 * @param {string} str A string of HTML 4 */ 5export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");
scrollToHide()
上滚动以显示HTML元素,向下滚动以将其隐藏。
1 /** 2 * 下滚动时隐藏HTML元素。 3 * @param {string} 元素的 id 4 * @param {string} distance in px ex: "100px" 5 */ 6export 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 */ 5export 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 27console.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 */ 6export 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 25console.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 */ 7export 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 */ 22export 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 */ 5export const formatNumber = (num) => num.toLocaleString(); 6 7// Example 8console.log(formatNumber(78899985)); // 78,899,985
我们还可以添加其他选项来获取其他数字格式,如货币、距离、权重等。
1export const toEGPCurrency = (num) => 2 num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" }); 3 4export const toUSDCurrency = (num) => 5 num.toLocaleString("en-US", { style: "currency", currency: "USD" }); 6 7console.log(toUSDCurrency(78899985)); // $78,899,985.00 8console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م.
toFormData()
每当我需要向服务器发送文件时,我就使用这个函数。
1/** 2 * Convert Objects to Form Data Format. 3 * @param {object} obj 4 */ 5export 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 */ 4export 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};
检查数组中的每个元素是否存在于另一个数组中。
1export 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};
你还有使用其他有用的函数吗?在评论里分享一下怎么样?
完~,我是小智,我要去刷碗去了。
代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug。
原文:https://dev.to/youssefzidan/j...
交流
文章每周持续更新,可以微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,另外关注公众号,后台回复福利,即可看到福利,你懂的。

本文转自 https://segmentfault.com/a/1190000039182225,如有侵权,请联系删除。
