1. 獲取一個隨機布林值 (true/false)
這個函式使用 Math.random() 方法回傳一個布林值(true 或 false),Math.random 將在 0 和 1 之間建一個亂數,之后我們檢查它是否高于或低于 0.5,這意味著得到真或假的幾率是 50%/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. 反轉字串
有幾種不同的方法來反轉一個字串,以下代碼是最簡單的方式之一,
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
4. 檢查當前 Tab 頁是否在前臺
我們可以通過使用 document.hidden 屬性來檢查當前標簽頁是否在前臺中,
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// Result: returns true or false depending on if tab is in view / focus
5. 檢查數字是否為偶數
最簡單的方式是通過使用模數運算子(%)來解決,如果你對它不太熟悉,這里是 Stack Overflow 的一個很好的圖解,
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. 檢查當前用戶是否為蘋果設備
我們可以使用 navigator.platform 來檢查當前用戶是否為蘋果設備,
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 坐標來進行滾動,如果我們將這些坐標設定為零,就可以滾到頁面的頂部,
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/254116.html
標籤:其他
