這篇文章將為大家詳細(xì)講解有關(guān)哪些JavaScript函數(shù)讓你的工作更方便,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
創(chuàng)新互聯(lián)是一家專業(yè)提供昌吉企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、H5頁(yè)面制作、小程序制作等業(yè)務(wù)。10年已為昌吉眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。
randomNumber()
獲取指定區(qū)間的隨機(jī)數(shù)。
** * 在最小值和最大值之間生成隨機(jī)整數(shù)。 * @param {number} min Min number * @param {number} max Max Number */ export const randomNumber = (min = 0, max = 1000) => Math.ceil(min + Math.random() * (max - min)); // Example console.log(randomNumber()); // 97
capitalize()
將字符串的第一個(gè)字母變?yōu)榇髮憽?/p>
/** * Capitalize Strings. * @param {string} s String that will be Capitalized */ export const capitalize = (s) => { if (typeof s !== "string") return ""; return s.charAt(0).toUpperCase() + s.slice(1); } // Example console.log(capitalize("cat")); // Cat
truncate();
這對(duì)于長(zhǎng)字符串很有用,特別是在表內(nèi)部。
/** * 截?cái)嘧址?... * @param {string} 要截?cái)嗟奈谋咀址?nbsp; * @param {number} 截?cái)嗟拈L(zhǎng)度 */ export const truncate = (text, num = 10) => { if (text.length > num) { return `${text.substring(0, num - 3)}...` } return text; } // Example console.log(truncate("this is some long string to be truncated")); // this is...
toTop();
滾到到底部,可以通過(guò) behavior 屬性指定滾動(dòng)速度狀態(tài)。
/** * Scroll to top */ export const toTop = () => { window.scroll({ top: 0, left: 0, behavior: "smooth" }); };
softDeepClone()
這個(gè)方法是經(jīng)常被用到的,因?yàn)橛辛怂覀兛梢陨疃瓤寺∏短讛?shù)組或?qū)ο蟆?/p>
不過(guò),這個(gè)函數(shù)不能與new Date()、NaN、undefined、function、Number、Infinity等數(shù)據(jù)類型一起工作。
你想深度克隆上述數(shù)據(jù)類型,可以使用 lodash 中的 cloneDeep() 函數(shù)。
/** * Deep cloning inputs * @param {any} input Input */ export const softDeepClone= (input) => JSON.parse(JSON.stringify(input));
appendURLParams() & getURLParams()
快速添加和獲取查詢字符串的方法,我通常使用它們將分頁(yè)元數(shù)據(jù)存儲(chǔ)到url。
/** * Appen query string and return the value in a query string format. * @param {string} key * @param {string} value */ export const appendURLParams = (key, value) => { const searchParams = new URLSearchParams(window.location.search).set(key, value); return searchParams.toString(); }; // example console.log(appendURLParams("name", "youssef")) // name=youssef /** * Get param name from URL. * @param {string} name */ export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name); // Example console.log(getURLParams(id)) // 5
getInnerHTML()
每當(dāng)服務(wù)器返回一串HTML元素時(shí),我都會(huì)使用它。
/** * 獲取HTML字符串的內(nèi)部Text * @param {string} str A string of HTML */ export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");
scrollToHide()
上滾動(dòng)以顯示HTML元素,向下滾動(dòng)以將其隱藏。
/** * 下滾動(dòng)時(shí)隱藏HTML元素。 * @param {string} 元素的 id * @param {string} distance in px ex: "100px" */ export const scrollToHide = (id, distance) => { let prevScrollpos = window.pageYOffset; window.onscroll = () => { const currentScrollPos = window.pageYOffset; if (prevScrollpos > currentScrollPos) { document.getElementById(id).style.transform = `translateY(${distance})`; } else { document.getElementById(id).style.transform = `translateY(-${distance})`; } prevScrollpos = currentScrollPos; }; };
humanFileSize ()
傳入字節(jié)為單位的文件,返回我們?nèi)粘K煜さ膯挝弧?/p>
/** * Converting Bytes to Readable Human File Sizes. * @param {number} bytes Bytes in Number */ export const humanFileSize = (bytes) => { let BYTES = bytes; const thresh = 1024; if (Math.abs(BYTES) < thresh) { return `${BYTES} B`; } const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; let u = -1; const r = 10 ** 1; do { BYTES /= thresh; u += 1; } while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1); return `${BYTES.toFixed(1)} ${units[u]}`; }; // Example console.log(humanFileSize(456465465)); // 456.5 MB
getTimes()
你是否有一個(gè)DDL,它每n分鐘顯示一天的時(shí)間?用這個(gè)函數(shù)。
/** * Getting an Array of Times + "AM" or "PM". * @param {number} minutesInterval * @param {number} startTime */ export const getTimes = (minutesInterval = 15, startTime = 60) => { const times = []; // time array const x = minutesInterval; // minutes interval let tt = startTime; // start time const ap = ["AM", "PM"]; // AM-PM // loop to increment the time and push results in array for (let i = 0; tt < 24 * 60; i += 1) { const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format const mm = tt % 60; // getting minutes of the hour in 0-55 format times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${ ap[Math.floor(hh / 12)] }`; // pushing data in array in [00:00 - 12:00 AM/PM format] tt += x; } return times; }; // Example console.log(getTimes()); /* [ "1:00 AM", "1:15 AM", "1:30 AM", "1:45 AM", "2:00 AM", "2:15 AM", "2:30 AM", // .... ] */
setLocalItem() & getLocalItem()
讓 LocalStorage 具有過(guò)期時(shí)間。
/** * Caching values with expiry date to the LocalHost. * @param {string} key Local Storage Key * @param {any} value Local Storage Value * @param {number} ttl Time to live (Expiry Date in MS) */ export const setLocalItem = (key, value, ttl = duration.month) => { const now = new Date(); // `item` is an object which contains the original value // as well as the time when it's supposed to expire const item = { value, expiry: now.getTime() + ttl, }; localStorage.setItem(key, JSON.stringify(item)); }; /** * Getting values with expiry date from LocalHost that stored with `setLocalItem`. * @param {string} key Local Storage Key */ export const getLocalItem = (key) => { const itemStr = localStorage.getItem(key); // if the item doesn't exist, return null if (!itemStr) { return null; } const item = JSON.parse(itemStr); const now = new Date(); // compare the expiry time of the item with the current time if (now.getTime() > item.expiry) { // If the item is expired, delete the item from storage // and return null localStorage.removeItem(key); return null; } return item.value; };
formatNumber()
/** * Format numbers with separators. * @param {number} num */ export const formatNumber = (num) => num.toLocaleString(); // Example console.log(formatNumber(78899985)); // 78,899,985
我們還可以添加其他選項(xiàng)來(lái)獲取其他數(shù)字格式,如貨幣、距離、權(quán)重等。
export const toEGPCurrency = (num) => num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" }); export const toUSDCurrency = (num) => num.toLocaleString("en-US", { style: "currency", currency: "USD" }); console.log(toUSDCurrency(78899985)); // $78,899,985.00 console.log(toEGPCurrency(78899985)); // ????????????? ?.?.
toFormData()
每當(dāng)我需要向服務(wù)器發(fā)送文件時(shí),我就使用這個(gè)函數(shù)。
/** * Convert Objects to Form Data Format. * @param {object} obj */ export const toFormData = (obj) => { const formBody = new FormData(); Object.keys(obj).forEach((key) => { formBody.append(key, obj[key]) }) return formBody; }
getScreenWidth()
獲取一個(gè)表示屏幕寬度的字符串。
/** * Detect screen width and returns a string representing the width of the screen. */ export const getScreenWidth = () => { const screenWidth = window.screen.width; if (screenWidth <= 425) return "mobile"; if (screenWidth <= 768) return "tablet"; if (screenWidth <= 1024) return "laptopSm"; if (screenWidth <= 1440) return "laptopLg"; if (screenWidth <= 2560) return "HD"; return screenWidth; };
檢查數(shù)組中的每個(gè)元素是否存在于另一個(gè)數(shù)組中。
export const containsAll = (baseArr, arr) => { let all = false; for (let i = 0; i < arr.length; i += 1) { if (baseArr.includes(arr[i])) { all = true; } else { all = false; return all; } } return all; };
關(guān)于哪些JavaScript函數(shù)讓你的工作更方便就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
本文題目:哪些JavaScript函數(shù)讓你的工作更方便
URL鏈接:http://www.chinadenli.net/article12/gecjgc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、手機(jī)網(wǎng)站建設(shè)、商城網(wǎng)站、搜索引擎優(yōu)化、外貿(mào)建站、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)