JavaScript 是一門神奇的語言,它的某些特性讓人捉摸不透,但其簡潔和靈活性也讓人愛不釋手。有些功能邏輯按常規思路可能需要不少代碼,但是利用某些 API 和語法特性,短短一行代碼就能完成!本文簡單列舉一些常用的一行代碼,希望對你有用。
1. 獲取隨機布爾值 (true/false)
Math.random()會返回 0 到1之間隨機的數字,因此可以利用返回值是否比 0.5小來返回隨機的布爾值。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
2. 反轉字符串
結合數組的反轉方法,可以反轉字符串:
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
3. 數組去重
面試常考題,偷懶的做法就是用Set。
let removeDuplicates = arr => [...new Set(arr)];
console.log(removeDuplicates(['foo', 'bar', 'bar', 'foo', 'bar']));
// ['foo', 'bar']
4. 判斷瀏覽器 Tab 窗口是否為活動窗口
利用document.hidden屬性可以判斷瀏覽器窗口是否可見(當前活動窗口)。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
5. 判斷數字奇偶
小學數學題,用% 2判斷就行:
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
6. 獲取日期對象的時間部分
日期對象的 .toTimeString()方法可以獲取時間格式的字符串,截取前面部分就可以了:
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"
console.log(timeFromDate(new Date()));
// Result: will log the current time
7. 數字截斷小數位
如果需要截斷浮點數的小數位(不是四舍五入),可以借助 Math.pow() 實現:
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726
8. 判斷 DOM 元素是否已獲得焦點
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
9. 判斷當前環境是否支持 touch 事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
10. 判斷是否為 Apple 設備
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
11. 滾動到頁面頂部
window.scrollTo() 方法接受x和y坐標參數,用于指定滾動目標位置。全都設置為 0,可以回到頁面頂部。注意:IE 不支持 .scrollTo()方法。
const goToTop = () => window.scrollTo(0, 0);
goToTop();
12. 求平均值
reduce的典型應用場景:數組求和。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
原文地址:https://mp.weixin.qq.com/s?__biz=MjM5OTM4MDgwOQ==&mid=2449414794&idx=1&sn=5db8c9064bbd5558ecd214ca2a28129d&chksm=b337e8ac844061ba804e12acbac13c304d77f8b7ba1ac7a204111dc15966c6af4e57d355db85&mpshare=1&