您好,登錄后才能下訂單哦!
這篇“實(shí)用的JavaScript單行代碼有哪些”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“實(shí)用的JavaScript單行代碼有哪些”文章吧。
1. 日期是否正確(有效)
此方法用于檢查給定日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 27, 2022 13:14:00"); // true
2. 知道一個(gè)日期是否對(duì)應(yīng)于當(dāng)前日期
就像將兩個(gè)日期轉(zhuǎn)換為相同格式并進(jìn)行比較一樣簡單。
是一個(gè) Date 實(shí)例。
const isCurrentDay = (date) => new Date().toISOString().slice(0, 10) === date.toISOString().slice(0, 10);
3. 如何知道一個(gè)日期是否在兩個(gè)日期之間
我們檢查過去的日期是否在最小-最大范圍內(nèi)。
<min>、<max> 和 <date> 是 Date 實(shí)例。
const isBetweenTwoDates = ( min, max, date) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
4. 計(jì)算兩個(gè)日期之間的間隔
此方法用于計(jì)算兩個(gè)日期之間的間隔。
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2022-08-27"), new Date("2022-12-25")) // 120
5. 如何知道約會(huì)是否在周末
getDay 方法返回一個(gè)介于 0 和 6 之間的數(shù)字,表示給定日期是星期幾。
是一個(gè) Date 實(shí)例。
const isWeekend = ( date ) => date.getDay() === 6 || date.getDay() === 0;
6. 檢查日期是否在一年內(nèi)
類似于我們過去檢查日期是否與當(dāng)前日期相對(duì)應(yīng)的情況。在這種情況下,我們獲取年份并進(jìn)行比較。
和是兩個(gè) Date 實(shí)例。
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. 將小時(shí)轉(zhuǎn)換為 AM-PM 格式
我們可以用數(shù)學(xué)表達(dá)式來判斷經(jīng)過的時(shí)間是否小于或等于13小時(shí),從而判斷是“上午”還是“下午”。
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
9. 格式化時(shí)間
此方法可用于將時(shí)間轉(zhuǎn)換為 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.將小時(shí)轉(zhuǎn)換為 AM-PM 格式
我們可以用數(shù)學(xué)表達(dá)式來判斷經(jīng)過的時(shí)間是否小于或等于13小時(shí),從而判斷是“上午”還是“下午”。
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
10.1 字符串的初始大寫
此方法用于將字符串的第一個(gè)字母大寫。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("hello world") // Hello world
10.2 句子首字母大寫
我們將第一個(gè)字母轉(zhuǎn)換為大寫字母,然后使用 <join.> 附加句子的其余字母
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;
11. 將一封信轉(zhuǎn)換成他的同事表情符號(hào)
const letterToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);
12.如何判斷一個(gè)字符串是不是回文
const isPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
13. 翻轉(zhuǎn)字符串
該方法用于翻轉(zhuǎn)字符串并返回翻轉(zhuǎn)后的字符串。
const reverse = str => str.split('').reverse().join(''); reverse('hello world'); // 'dlrow olleh'
14. 隨機(jī)字符串
此方法用于生成隨機(jī)字符串。
//方式一 const randomString = () => Math.random().toString(36).slice(2); randomString(); //方式二 const randomstr = Math.random().toString(36).substring(7)
15. 字符串截?cái)?/strong>
此方法將字符串截?cái)酁橹付ㄩL度。
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 || '';
數(shù)字
17.如何計(jì)算一個(gè)數(shù)的階乘
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
18. 如何獲得一個(gè)數(shù)的斐波那契數(shù)列
const getFibonacci = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
19. 如何求一個(gè)數(shù)的階乘
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
20. 判斷一個(gè)數(shù)是奇數(shù)還是偶數(shù)
此方法用于確定數(shù)字是奇數(shù)還是偶數(shù)。
const isEven = num => num % 2 === 0; isEven(996);
21. 得到一組數(shù)字的平均值
const average = (.. .args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4, 5); // 3
22. 從兩個(gè)整數(shù)中確定隨機(jī)整數(shù)
此方法用于獲取兩個(gè)整數(shù)之間的隨機(jī)整數(shù)。
const random = (min, max) => Math.floor(Math.random() * (max — min + 1) + min); random(1, 50);
23. 四舍五入到指定位數(shù)
此方法可用于將數(shù)字四舍五入到指定的數(shù)字。
const random = (min, max) => Math.floor(Math.random() * (max — min + 1) + min); random(1, 50);
數(shù)組
24. 將一個(gè)數(shù)組復(fù)制到另一個(gè)數(shù)組
const copyToArray = (arr) => [...arr];
25. 從數(shù)組中獲取唯一元素
const getUnique = (arr) => [...new Set(arr)];
26. 隨機(jī)排列
以下代碼段以非常有效的方式打亂數(shù)組。
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
27. 按屬性對(duì)數(shù)組進(jìn)行分組
const groupBy = (arr, groupFn) => arr.reduce( (grouped, obj) => ({...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }),{});
28. 檢查兩個(gè)數(shù)組是否包含相同的值
我們可以使用 Array.sort() 和 Array.join() 方法來檢查兩個(gè)數(shù)組是否包含相同的值。
const containSameValues= (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');
29. 檢測對(duì)象是否為空
該方法用于檢測 JavaScript 對(duì)象是否為空。
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
30. 切換變量
可以使用以下形式交換兩個(gè)變量的值,而無需應(yīng)用第三個(gè)變量。
[foo, bar] = [bar, foo];
31. 隨機(jī)布爾值
此方法返回一個(gè)隨機(jī)布爾值。使用 Math.random(),你可以得到一個(gè) 0-1 的隨機(jī)數(shù),并將它與 0.5 進(jìn)行比較,有一半的概率得到一個(gè)真值或假值。
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(() => {}); // function
33. 顏色轉(zhuǎn)換
33.1將 HEX "#00000" 轉(zhuǎn)換為 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)轉(zhuǎn)換為 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 隨機(jī)生成一種十六進(jìn)制顏色
此方法用于獲取隨機(jī)的十六進(jìn)制(HEX)顏色值。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; randomHex();
34. 溫度與華氏度轉(zhuǎn)換
34.1 轉(zhuǎn)換為華氏溫度
const toFahrenheit= (celsius) => (celsius * 9) / 5 + 32;
34.2 轉(zhuǎn)換為攝氏度
const toCelsius= (fahrenheit) => (fahrenheit- 32) * 5 / 9;
35. 確定當(dāng)前選項(xiàng)卡是否處于活動(dòng)狀態(tài)
此方法用于檢查當(dāng)前選項(xiàng)卡是否處于活動(dòng)狀態(tài)。
const isTabInView = () => !document.hidden;
36. 判斷當(dāng)前設(shè)備是否為蘋果設(shè)備
此方法用于檢查當(dāng)前設(shè)備是否為 Apple 設(shè)備。
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. 檢查函數(shù)是否為異步函數(shù)
const isAsyncFunction = (f) => Object.prototype.toString.call(f) === '[object AsyncFunction]';
39. 如何知道一段代碼是否在瀏覽器中運(yùn)行
const runningInBrowser = typeof window === 'object' && typeof document === 'object';
40. 如何知道一段代碼是否在node中運(yùn)行
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. 滾動(dòng)的元素滾動(dòng)到頂部
滾動(dòng)元素的一種單行方法是使用方法。
//方式一 const toTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
43. 滾動(dòng)的元素滾動(dòng)到底部
const toBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
44. 導(dǎo)航到頁面頂部
此方法用于返回頁面頂部。
const goToTop = () => window.scrollTo(0, 0); goToTop();
45. 是否滾動(dòng)到頁面底部
該方法用于判斷頁面是否在底部。
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
46.將 JSON 轉(zhuǎn)換為map
這個(gè)函數(shù)可以讓我們以簡單的方式將 Map 對(duì)象轉(zhuǎn)換為 JSON 字符串。
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
47.生成一個(gè)128位的UUID
此函數(shù)允許我們生成具有 128 位值的 UUID,用于唯一標(biāo)識(shí)對(duì)象或?qū)嶓w。
const generateUUID = (a) => a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( /[018]/g, generateUUID);
48. 重定向到一個(gè) URL
此方法用于重定向到新 URL。
const redirect = url => location.href = url redirect("https://www.google.com/")
49. 打開瀏覽器打印框
該方法用于打開瀏覽器的打印框。
const showPrintDialog = () => window.print()
50.刪除所有cookies
該方法使用 document.cookie 訪問 cookie 并清除網(wǎng)頁上存儲(chǔ)的所有 cookie。
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
以上就是關(guān)于“實(shí)用的JavaScript單行代碼有哪些”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。