
英文 | https://medium.com/@cookbug/13-lines-of-javascript-code-make-you-look-like-a-master-95eaac233545
翻譯 | 楊小愛
Javascript可以做很多神奇的事情,還有很多東西要學。今天我們介紹13個簡短的代碼片段。
1、擷取随機布爾值(真/假)
使用 Math.random() 會傳回一個從 0 到 1 的随機數,然後,判斷它是否大于 0.5,你會得到一個有 50% 機率為 True 或 False 的值。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
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、判斷目前标簽是否可見
浏覽器可以打開很多标簽,下面的代碼片段是判斷目前标簽是否為活動标簽。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
5、判斷數字是奇數還是偶數
模數運算符 % 可以很好地完成這個任務。
const isEven = num => num% 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
6、從Date對象中擷取時間
使用Date對象的.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: return the current time
7、保留指定的小數位
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: If it is in focus, it will return True, otherwise it will return False
9、檢查目前使用者是否支援觸摸事件
const touchSupported = () => {
(‘ontouchstart’ in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: If touch event is supported, it will return True, otherwise it will return False
10、檢查目前使用者是否為蘋果裝置
可以使用 navigator.platform 來判斷目前使用者是否是蘋果裝置。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: Apple device will return True
11、滾動到頁面頂部
window.scrollTo() 會滾動到指定坐标,如果坐标設定為(0, 0),會傳回到頁面頂部。
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll to the top
12、擷取所有參數的平均值
您可以使用 reduce() 函數計算所有參數的平均值。
const average = (…args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
13、轉換華氏/攝氏度
不再怕處理溫度機關,下面兩個函數就是兩個溫度機關的互相轉換。
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
本文完~