分享50個超級有用的JavaScript單行代碼(推薦!)
前言
在這篇文章中,我列出了一個系列的50個 JavaScript 單行代碼,它們在使用 vanilla js(≥ ES6)進行開發(fā)時非常有用。它們也是使用該語言在最新版本中為我們提供的所有功能來解決問題的優(yōu)雅方式。
我將它們分為以下5大類:
- 日期
- 字符串
- 數字
- 數組
- 工具
事不宜遲,我馬上開始的,我希望你發(fā)現他們對你有幫助!
日期
1. 日期是否正確(有效)
此方法用于檢查給定日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 27, 2022 13:14:00"); // true2. 知道一個日期是否對應于當前日期
就像將兩個日期轉換為相同格式并進行比較一樣簡單。
是一個 Date 實例。
const isCurrentDay = (date) => new Date().toISOString().slice(0, 10) === date.toISOString().slice(0, 10);
3. 如何知道一個日期是否在兩個日期之間
我們檢查過去的日期是否在最小-最大范圍內。
<min>、<max> 和 <date> 是 Date 實例。
const isBetweenTwoDates = ( min, max, date) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
4. 計算兩個日期之間的間隔
此方法用于計算兩個日期之間的間隔。
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2022-08-27"), new Date("2022-12-25")) // 1205. 如何知道約會是否在周末
getDay 方法返回一個介于 0 和 6 之間的數字,表示給定日期是星期幾。
是一個 Date 實例。
const isWeekend = ( date ) => date.getDay() === 6 || date.getDay() === 0;
6. 檢查日期是否在一年內
類似于我們過去檢查日期是否與當前日期相對應的情況。在這種情況下,我們獲取年份并進行比較。
和是兩個 Date 實例。
const isInAYear = (date, year) => date.getUTCFullYear() === new Date(`${year}`).getUTCFullYear();
7. 確定日期所在的一年中的哪一天
此方法用于檢測給定日期所在的一年中的哪一天。
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // 239
8. 將小時轉換為 AM-PM 格式
我們可以用數學表達式來判斷經過的時間是否小于或等于13小時,從而判斷是“上午”還是“下午”。
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
9. 格式化時間
此方法可用于將時間轉換為 hh:mm:ss 格式。
const timeFromDate = date => date.toTimeString().slice(0, 8); timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00 timeFromDate(new Date()); // now time 09:00:00
10.將小時轉換為 AM-PM 格式
我們可以用數學表達式來判斷經過的時間是否小于或等于13小時,從而判斷是“上午”還是“下午”。
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;字符串
10.1 字符串的初始大寫
此方法用于將字符串的第一個字母大寫。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world") // Hello world10.2 句子首字母大寫
我們將第一個字母轉換為大寫字母,然后使用 <join.> 附加句子的其余字母
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;
11. 將一封信轉換成他的同事表情符號
const letterToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);
12.如何判斷一個字符串是不是回文
const isPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split('').reverse().join('');13. 翻轉字符串
該方法用于翻轉字符串并返回翻轉后的字符串。
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'14. 隨機字符串
此方法用于生成隨機字符串。
//方式一 const randomString = () => Math.random().toString(36).slice(2); randomString(); //方式二 const randomstr = Math.random().toString(36).substring(7)
15. 字符串截斷
此方法將字符串截斷為指定長度。
const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'16. 從字符串中刪除 HTML
此方法用于從字符串中刪除 HTML 元素。
const stripHtml = html => (new DOMParser().parseFromString(html,'text/html')).body.textContent || '';
數字
17.如何計算一個數的階乘
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
18. 如何獲得一個數的斐波那契數列
const getFibonacci = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
19. 如何求一個數的階乘
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
20. 判斷一個數是奇數還是偶數
此方法用于確定數字是奇數還是偶數。
const isEven = num => num % 2 === 0; isEven(996);
21. 得到一組數字的平均值
const average = (.. .args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4, 5); // 3
22. 從兩個整數中確定隨機整數
此方法用于獲取兩個整數之間的隨機整數。
const random = (min, max) => Math.floor(Math.random() * (max — min + 1) + min); random(1, 50);
23. 四舍五入到指定位數
此方法可用于將數字四舍五入到指定的數字。
const random = (min, max) => Math.floor(Math.random() * (max — min + 1) + min); random(1, 50);
數組
24. 將一個數組復制到另一個數組
const copyToArray = (arr) => [...arr];
25. 從數組中獲取唯一元素
const getUnique = (arr) => [...new Set(arr)];
26. 隨機排列
以下代碼段以非常有效的方式打亂數組。
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
27. 按屬性對數組進行分組
const groupBy = (arr, groupFn) => arr.reduce( (grouped, obj) => ({...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }),{});28. 檢查兩個數組是否包含相同的值
我們可以使用 Array.sort() 和 Array.join() 方法來檢查兩個數組是否包含相同的值。
const containSameValues= (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');工具
29. 檢測對象是否為空
該方法用于檢測 JavaScript 對象是否為空。
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
30. 切換變量
可以使用以下形式交換兩個變量的值,而無需應用第三個變量。
[foo, bar] = [bar, foo];
31. 隨機布爾值
此方法返回一個隨機布爾值。使用 Math.random(),你可以得到一個 0-1 的隨機數,并將它與 0.5 進行比較,有一半的概率得到一個真值或假值。
const randomBoolean = () => Math.random() >= 0.5; randomBoolean();
32. 獲取變量的類型
該方法用于獲取變量的類型。
const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
trueTypeOf(‘'); // string
trueTypeOf(0); // number
trueTypeOf(); // undefined
trueTypeOf(null); // null
trueTypeOf({}); // object
trueTypeOf([]); // array
trueTypeOf(0); // number
trueTypeOf(() => {}); // function33. 顏色轉換
33.1將 HEX "#00000" 轉換為 RGB(0,0,0)
const toRGB= (hex) =>
hex.
replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}$$`)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));33.2將 RGB(0,0,0)轉換為 HEX"#00000"
const rgbToHex= (r,g,b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(255, 255, 255); // '#ffffff'
33.3 隨機生成一種十六進制顏色
此方法用于獲取隨機的十六進制(HEX)顏色值。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();34. 溫度與華氏度轉換
34.1 轉換為華氏溫度
const toFahrenheit= (celsius) => (celsius * 9) / 5 + 32;
34.2 轉換為攝氏度
const toCelsius= (fahrenheit) => (fahrenheit- 32) * 5 / 9;
35. 確定當前選項卡是否處于活動狀態(tài)
此方法用于檢查當前選項卡是否處于活動狀態(tài)。
const isTabInView = () => !document.hidden;
36. 判斷當前設備是否為蘋果設備
此方法用于檢查當前設備是否為 Apple 設備。
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform); isAppleDevice();
37. 如何清除瀏覽器的所有cookies
const clearAllCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));
38. 檢查函數是否為異步函數
const isAsyncFunction = (f) => Object.prototype.toString.call(f) === '[object AsyncFunction]';
39. 如何知道一段代碼是否在瀏覽器中運行
const runningInBrowser = typeof window === 'object' && typeof document === 'object';
40. 如何知道一段代碼是否在node中運行
const runningInNode= typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
41. 檢測暗模式
這是一種非常方便的方法來檢查用戶是否在其瀏覽器上啟用了黑暗模式。
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)42. 滾動的元素滾動到頂部
滾動元素的一種單行方法是使用方法。
//方式一
const toTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" });43. 滾動的元素滾動到底部
const toBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" });44. 導航到頁面頂部
此方法用于返回頁面頂部。
const goToTop = () => window.scrollTo(0, 0); goToTop();
45. 是否滾動到頁面底部
該方法用于判斷頁面是否在底部。
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
46.將 JSON 轉換為map
這個函數可以讓我們以簡單的方式將 Map 對象轉換為 JSON 字符串。
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
47.生成一個128位的UUID
此函數允許我們生成具有 128 位值的 UUID,用于唯一標識對象或實體。
const generateUUID = (a) => a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( /[018]/g, generateUUID);
48. 重定向到一個 URL
此方法用于重定向到新 URL。
const redirect = url => location.href = url
redirect("https://www.google.com/")49. 打開瀏覽器打印框
該方法用于打開瀏覽器的打印框。
const showPrintDialog = () => window.print()
50.刪除所有cookies
該方法使用 document.cookie 訪問 cookie 并清除網頁上存儲的所有 cookie。
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));總結
到此這篇關于50個超級有用的JavaScript單行代碼的文章就介紹到這了,更多相關JS單行代碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
微信小程序完美解決scroll-view高度自適應問題的方法
這篇文章主要介紹了微信小程序完美解決scroll-view高度自適應問題的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08

