16個(gè) JavaScript 單行代碼幫助你提升開發(fā)水平
今天我們將分享16個(gè)實(shí)用的單行 JavaScript 代碼,旨在提高你的編碼效率并簡(jiǎn)化你的代碼。從數(shù)組和字符串操作到異步編程和面向?qū)ο缶幊痰雀呒?jí)概念,我們都能滿足你的要求。
現(xiàn)在,讓我們開始吧!
1、獲取數(shù)組中的隨機(jī)元素
使用 Math.random() 函數(shù)結(jié)合數(shù)組的長(zhǎng)度,從數(shù)組中獲取隨機(jī)元素非常輕松:
const arr = [1, 2, 3, 4, 5];
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement);
2、輕松展平數(shù)組
使用 reduce() 和 concat() 函數(shù)將嵌套數(shù)組展平為單層:
const arr = [[1, 2], [3, 4], [5, 6]];
const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []);
console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6]
3、按屬性對(duì)數(shù)組進(jìn)行排序
只需根據(jù)特定屬性的值對(duì)對(duì)象數(shù)組進(jìn)行排序:
const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1));
4、刪除特定元素
你可以輕松地從數(shù)組中過(guò)濾掉不需要的元素:
const removedArray = array.filter((item) => item !== elementToRemove);
5、檢查數(shù)組中的重復(fù)項(xiàng)
檢測(cè)數(shù)組是否包含任何重復(fù)項(xiàng):
const hasDuplicates = (array) => new Set(array).size !== array.length;
6、數(shù)組值存在性檢查
快速確定數(shù)組是否包含特定值:
const hasValue = arr.includes(value);
7、將首字母大寫
將字符串的首字母轉(zhuǎn)換為大寫:
const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
8、生成隨機(jī)整數(shù)
在內(nèi)創(chuàng)建一個(gè)隨機(jī)整數(shù)特定范圍:
const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
9、獲取隨機(jī)字符串
生成指定長(zhǎng)度的隨機(jī)字符串:
const randomStr = Math.random().toString(36).substring(2, length);
10、交換變量值
使用解構(gòu)和 rest 運(yùn)算符輕松交換兩個(gè)變量的值:
let a = 1, b = 2;
[b, a] = [a, b];
console.log(a, b); // 2, 1
11、將字符串轉(zhuǎn)換為駝峰式大小寫
輕松將任何字符串轉(zhuǎn)換為駝峰式大小寫格式:
const str = 'hello world';
const camelCase = str.replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase());
console.log(camelCase); // "helloWorld"
12、計(jì)算時(shí)間間隔
查找兩個(gè)日期之間的天數(shù):
const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24));
13、發(fā)現(xiàn)一年中的哪一天
計(jì)算特定日期屬于一年中的哪一天:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
14、復(fù)制到剪貼板
輕松將文本復(fù)制到剪貼板:
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
15、識(shí)別變量類型
確定 JavaScript 中任何變量的類型:
const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
getType(''); // string
16、檢查對(duì)象是否為空
快速驗(yàn)證對(duì)象是否沒(méi)有屬性:
const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
以上就是我今天與你分享的16個(gè)JavaScript 單行代碼,不僅可以節(jié)省時(shí)間,而且還有助于編寫更干凈、更高效的代碼。