天天看點

13個酷炫的JavaScript一行程式

1. 獲得一個随機的布爾值(

true

/

false

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());      

2. 檢查所提供的日期是否為工作日

getDay() 方法可傳回一周(0~6)的某一天的數字。

注意: 星期天為 0, 星期一為 1, 以此類推。

const isWeekday = (date) => date.getDay() % 6 !== 0;

console.log(isWeekday(new Date(2021, 7, 6)));
// true  因為是周五

console.log(isWeekday(new Date(2021, 7, 7)));
// false 因為是周六      

3.反轉字元串 

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// 'dlrow olleh'      

4.檢查目前标簽是否隐藏

場外:無意間發現愛奇藝廣告播放時間居然是在目前标簽頁激活的時候才會進行倒計時,離開目前标簽頁的時候,倒計時停止,百度一下發現

document.hidden

這個東東。

Document.hidden

 (隻讀屬性)傳回布爾值,表示頁面是(

true

)否(

false

)隐藏。

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();      

5. 檢查一個數字是偶數還是奇數

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// true
console.log(isEven(3));
// false      

6. 從一個日期擷取時間

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// "17:30:00"

console.log(timeFromDate(new Date()));
// 列印目前的時間      

7. 保留 n 位小數

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// 事例
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)
// 如果在焦點中傳回true,如果不在焦點中傳回 false      

9. 檢查目前浏覽器是否支援觸摸事件

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// 如果支援觸摸事件,将傳回true,如果不支援則傳回false。      

10. 檢查目前浏覽器是否在蘋果裝置上

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);      

11. 滾動到頁面頂部

const goToTop = () => window.scrollTo(0, 0);
goToTop();      

12. 擷取參數的平均數值

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// 2.5      

13.華氏/攝氏轉換

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// 事例
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0