本篇文章給大家介紹20+個(gè)JavaScript單行代碼,可以幫助你像專(zhuān)業(yè)人士一樣編寫(xiě)代碼霍比。有一定的參考價(jià)值幕袱,有需要的朋友可以參考一下,希望對(duì)大家有所幫助悠瞬。
JavaScript不斷發(fā)展壯大们豌,
因?yàn)樗亲钊菀咨鲜值恼Z(yǔ)言之一,因此為市場(chǎng)上的新成為技術(shù)怪才
打開(kāi)了大門(mén)浅妆。(問(wèn)號(hào)臉望迎?)
的確,JavaScript可以做很多出色的事情凌外!還有很多東西要學(xué)習(xí)辩尊。
而且,無(wú)論你是JavaScript的新手還是更多的專(zhuān)業(yè)開(kāi)發(fā)人員康辑,學(xué)習(xí)新知識(shí)總是一件好事摄欲。
本文整理了一些非常有用的單行代碼(20+),這些單行代碼可以幫助你提高工作效率并可以幫助調(diào)試代碼疮薇。
什么是單行代碼胸墙?
單行代碼是一種代碼實(shí)踐,其中我們僅用一行代碼執(zhí)行某些功能按咒。
01-隨機(jī)獲取布爾值
此函數(shù)將使用Math.random()
方法返回布爾值(真或假)劳秋。
Math.random
創(chuàng)建一個(gè)介于0和1之間的隨機(jī)數(shù),然后我們檢查它是否大于或小于0.5胖齐。
這意味著有50/50的機(jī)會(huì)會(huì)得到對(duì)或錯(cuò)玻淑。
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
02-檢查日期是否為周末
通過(guò)此功能,你將能夠檢查提供的日期是工作日還是周末呀伙。
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
03-檢查數(shù)字是偶數(shù)還是奇數(shù)
簡(jiǎn)單的實(shí)用程序功能补履,用于檢查數(shù)字是偶數(shù)還是奇數(shù)。
const isEven = (num) => num % 2 === 0;
console.log(isEven(5));
// false
console.log(isEven(4));
// true
04-獲取數(shù)組中的唯一值(數(shù)組去重)
從數(shù)組中刪除所有重復(fù)值的非常簡(jiǎn)單的方法剿另。此函數(shù)將數(shù)組轉(zhuǎn)換為Set箫锤,然后返回?cái)?shù)組。
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
05-檢查變量是否為數(shù)組
一種檢查變量是否為數(shù)組的干凈簡(jiǎn)便的方法雨女。
當(dāng)然谚攒,也可以有其他方法
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
06-在兩個(gè)數(shù)字之間生成一個(gè)隨機(jī)數(shù)
這將以?xún)蓚€(gè)數(shù)字為參數(shù),并將在這兩個(gè)數(shù)字之間生成一個(gè)隨機(jī)數(shù)氛堕!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
07-生成隨機(jī)字符串(唯一ID馏臭?)
也許你需要臨時(shí)
的唯一ID,這是一個(gè)技巧讼稚,你可以使用它在旅途中生成隨機(jī)字符串括儒。
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
08-滾動(dòng)到頁(yè)面頂部
所述window.scrollTo()
方法把一個(gè)X
和Y
坐標(biāo)滾動(dòng)到绕沈。
如果將它們?cè)O(shè)置為零和零,我們將滾動(dòng)到頁(yè)面頂部帮寻。
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
09-切換布爾
切換布爾值是非痴Ш基本的編程問(wèn)題之一,可以通過(guò)許多不同的方法來(lái)解決固逗。
代替使用if語(yǔ)句來(lái)確定將布爾值設(shè)置為哪個(gè)值浅蚪,你可以使用函數(shù)使用!翻轉(zhuǎn)當(dāng)前值烫罩。非
運(yùn)算符掘鄙。
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
//or
const toggleBool = b => !b;
10-交換兩個(gè)變量
下面的代碼是不使用第三個(gè)變量而僅使用一行代碼即可交換兩個(gè)變量的更簡(jiǎn)單方法之一。
[foo, bar] = [bar, foo];
11-計(jì)算兩個(gè)日期之間的天數(shù)
要計(jì)算兩個(gè)日期之間的天數(shù)嗡髓,
我們首先找到兩個(gè)日期之間的絕對(duì)值,然后將其除以86400000(等于一天中的毫秒數(shù))收津,最后將結(jié)果四舍五入并返回饿这。
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
12-將文字復(fù)制到剪貼板
PS:你可能需要添加檢查以查看是否存在navigator.clipboard.writeText
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text);
};
13-合并多個(gè)數(shù)組的不同方法
有兩種合并數(shù)組的方法。其中之一是使用concat
方法撞秋。另一個(gè)使用擴(kuò)展運(yùn)算符(…
)长捧。
PS:我們也可以使用“設(shè)置”對(duì)象從最終數(shù)組中復(fù)制任何內(nèi)容。
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
14-獲取javascript語(yǔ)言的實(shí)際類(lèi)型
人們有時(shí)會(huì)使用庫(kù)來(lái)查找JavaScript中某些內(nèi)容的實(shí)際類(lèi)型吻贿,這一小技巧可以節(jié)省你的時(shí)間(和代碼大写帷)。
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
15-在結(jié)尾處截?cái)嘧址?/h2>
需要從頭開(kāi)始截?cái)嘧址肆校@不是問(wèn)題肌割!
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(
truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
16-從中間截?cái)嘧址?/h2>
從中間截?cái)嘧址趺礃樱?/p>
該函數(shù)將一個(gè)字符串作為第一個(gè)參數(shù),然后將我們需要的字符串大小作為第二個(gè)參數(shù)帐要,然后從第3個(gè)和第4個(gè)參數(shù)開(kāi)始和結(jié)束需要多少個(gè)字符
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // 需要的字符串大小
13, // 從原始字符串第幾位開(kāi)始截取
17, // 從原始字符串第幾位停止截取
),
);
// A long story ... eventually ends!
17-大寫(xiě)字符串
好吧把敞,不幸的是,JavaScript
沒(méi)有內(nèi)置函數(shù)來(lái)大寫(xiě)字符串榨惠,但是這種解決方法可以實(shí)現(xiàn)奋早。
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
18-檢查當(dāng)前選項(xiàng)卡是否在視圖/焦點(diǎn)內(nèi)
此簡(jiǎn)單的幫助程序方法根據(jù)選項(xiàng)卡是否處于視圖/焦點(diǎn)狀態(tài)而返回true
或false
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
19-檢查用戶(hù)是否在Apple設(shè)備上
如果用戶(hù)使用的是Apple
設(shè)備,則返回true
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
20-三元運(yùn)算符
當(dāng)你只想在一行中編寫(xiě)if..else
語(yǔ)句時(shí)赠橙,這是一個(gè)很好的代碼保護(hù)程序耽装。
// Longhand
const age = 18;
let greetings;
if (age < 18) {
greetings = 'You are not old enough';
} else {
greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
21-短路評(píng)估速記
在將變量值分配給另一個(gè)變量時(shí),可能要確保源變量不為null期揪,未定義或?yàn)榭铡?br> 可以編寫(xiě)帶有多個(gè)條件的long if語(yǔ)句掉奄,也可以使用短路評(píng)估。
// Longhand
if (name !== null || name !== undefined || name !== '') {
let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';
希望對(duì)你有所幫助!
英文原文地址:https://dev.to/ovi/20-javascript-one-liners-that-will-help-you-code-like-a-pro-4ddc
更多編程相關(guān)知識(shí)凤薛,請(qǐng)?jiān)L問(wèn):編程入門(mén);用取绰姻!