十個 JavaScript 單行代碼,讓你顯得更專業
今天,我將與你分享 10 個 JavaScript 單行代碼,它們將讓你顯得更專業!
1. 獲取隨機布爾值(真/假)
此函數將使用 Math.random() 方法生成一個布爾值(真或假)。 使用 Math.random 將生成一個介于 0 和 1 之間的隨機數,然后我們將確定它是高于還是低于 0.5。 因此,有 50% 的概率接收到真或假。
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)));
3. 翻轉字符串
這里有幾種不同的方法來轉動字符串。 使用 join()、reverse() 和 split() 技術,這是最簡單的技術之一。
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 上,如果你不太熟悉的話,有一個很棒的圖形解釋。
const isEven = num => num % 2 === 0;console.log(isEven(2));
6. 驗證組件現在是否處于焦點位置
document.activeElement 屬性可用于確定元素現在是否是焦點。
const elementIsInFocus = (el) => (el === document.activeElement);elementIsInFocus(anyElement)
// Result: will return true if in focus, false if not in focus
7. 驗證當前用戶是否支持觸摸事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}console.log(touchSupported());
8.確定平均參數值
為了獲得我們為此函數提供的輸入的平均值,我們可以使用 reduce 方法。
const average = (args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);
9. 將攝氏度轉換為華氏度
管理溫度有時會很困難,你可以使用這兩個例程在華氏溫度和攝氏溫度之間進行轉換。
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15);
celsiusToFahrenheit(0);
celsiusToFahrenheit(-20);
fahrenheitToCelsius(32);
10.驗證用戶是否使用蘋果設備
為了確定當前用戶是否在使用 Apple 設備,我們可以使用 navigator.platform。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);
總結
以上就是我跟大家分享的全部內容,希望對你有用,如果你覺得還不錯的話,請點贊我,關注我,并與你的開發者朋友一起來分享它。
感謝你的閱讀,編程愉快!