
英文 | https://medium.com/dailyjs/13-javascript-one-liners-thatll-make-you-look-like-a-pro-29a27b6f51cb
翻譯 | web前端開發公衆号(ID:web_qdkf)
JavaScript可以做很多令人驚奇的事情!
從複雜的架構到處理API,都需要學習很多東西。
但是,它也可以讓你僅用一行代碼就可以完成一些很棒的工作。
學習這13個JavaScript單行式代碼,讓你看起來更像專業人士!
1、随機擷取布爾值(true/false)
此函數将使用Math.random()方法傳回布爾值(真或假)。Math.random将建立一個介于0和1之間的随機數,然後我們檢查它是否大于或小于0.5。這意味着你有各50%的機會得到真或假值。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// Result: a 50/50 change on returning true of false
2、判斷給的日期是否為工作日
使用此方法,你将可以判斷函數中提供的日期是工作日還是雙休日。
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)
3、反轉字元串
用不同的方式可以反轉字元串。可以使用最簡單的split(),reverse()和join()方法。
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
4、判斷目前頁籤是否在視圖/焦點中
我們可以使用document.hidden屬性檢查目前标簽頁是否在視圖/焦點中。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// Result: returns true or false depending on if tab is in view / focus
5、判斷數字是偶數還是奇數
可以使用模運算符(%)解決的超簡單任務。如果你不太熟悉它,這是有關Stack Overflow的直覺說明(位址:https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator/17525046#17525046)
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、檢查元素目前是否處于焦點
我們可以使用document.activeElement屬性檢查元素目前是否處于焦點。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: will return true if in focus, false if not in focus
9、檢查目前使用者是否支援觸摸事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: will return true if touch events are supported, false if not
10、檢查目前使用者是否在Apple裝置上
我們可以navigator.platform用來檢查目前使用者是否在Apple裝置上。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device
11、滾動到頁面頂部
window.scrollTo()方法将使用x和y坐标滾動到。如果将它們設定為零和零,則将滾動到頁面頂部。
注意:Internet Explorer不支援該.scrollTo()方法。
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page
12、擷取參數的平均值
我們可以使用reduce方法擷取在此函數中提供的參數的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
13、轉換華氏/攝氏
最後一個是2合1!
應對溫度有時會造成混亂。這兩個功能将幫助你将華氏溫度轉換為攝氏溫度,反之亦然。
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
謝謝閱讀!希望你今天學到了一些新知識。
本文完~