Javascript可以做很多令人驚奇的事情,我也還有很多東西要學,今天我們介紹12個簡短而實用的代碼片段,幫助你提升工作效率。

1、判斷一個數是奇數還是偶數
模運算符 % 做得很好。
const IsEven = num num % 2 === 0;console.log(IsEven(2));// Result: trueconsole.log(IsEven(3));// Result: false
2、判斷日期是否為工作日
檢查給定日期是否為工作日。
const isWorkday = (date) => date.getDay() % 6 !== 0; console.log(isWorkday(new Date("2022/10/17"))); // Result: true (Monday) console.log(isWorkday(new Date("2022/10/16"))); // Result: false (Sumday)
3、獲取隨機布爾值(真/假)
使用 Math.random() 會返回一個介于 0 和 1 之間的隨機數,然后判斷是否大于 0.5 會得到一個有 50% 概率為 True 或 False 的值。
const randomBool = () Math.random() >= 0.5;console.log(randomBool());
4、從日期對象獲取時間
使用 Date 對象的 .toTimeString() 方法將其轉換為時間字符串,然后截取該字符串。
const timeBeginDate = date date.toTimeString().slice(0, 8); console.log(timeBeginDate(new Date(2022, 8, 10, 15, 30, 21))); // Result: "15:30:21" console.log(timeBeginDate(new Date())); // Result: return current time
5、滾動到頁面頂部
window.scrollTo() 會滾動到指定坐標,如果坐標設置為(0, 0),會返回到頁面頂部。
const toTop = () window.scrollTo(0, 0); toTop();
6、反轉字符串
反轉字符串的方法有很多,這里是最簡單的一種,使用 split()、reverse() 和 join()
const reverse = str str.split('').reverse().join('');
console.log(reverse('hello maxwell')); //Result: llewxam olleh
7、確定當前選項卡是否可見
瀏覽器可以打開很多標簽,下面的代碼段是判斷當前標簽是否為活動標簽。
const isBrowserTabInView = () document.hidden; isBrowserTabInView();
8、檢查指定元素是否被聚焦
你可以使用 document.activeElement 來確定元素是否處于焦點中。
const elementIsFocus = (el) => (el === document.activeElement); elementIsFocus(anyElement) // Returns True if it is in focus, otherwise returns False
9、判斷當前用戶是否支持觸摸事件
const touchSupported = () ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch); } console.log(touchSupported()); // Returns True if touch events are supported, otherwise returns False
10、判斷當前用戶是否為 Apple 設備
你可以使用 navigator.platform 來確定當前用戶是否是 Apple 設備。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);// If it is an Apple device it will return True otherwise it will return False
11、獲取所有參數的平均值
reduce() 函數可用于計算所有參數的平均值。
const average = (...args) => args.reduce((a, b) => var avg = average(6,10, 8, 12); console.log(avg); // Result: 9
12、轉換華氏/攝氏度
不要再害怕處理溫度單位了,下面兩個函數就是兩個溫度單位的相互轉換。
const celsiusToFahrenheit = (celsius) => celsius * 9 / 5 + 32; const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5 / 9; // Examples console.log(celsiusToFahrenheit(20)); // 68 console.log(celsiusToFahrenheit(0)); // 32 console.log(celsiusToFahrenheit(-15)); // 5 console.log(celsiusToFahrenheit(35)); // 95
寫在最后
以上就是我今天跟你分享的全部內容,如果你覺得有用的話,請記得點贊,關注我,我將與你分享更多實用的開發技巧。