13 個(gè) JavaScript 代碼技巧,讓你看起來像個(gè)專業(yè)高手

英文 | https://medium.com/@cookbug/13-lines-of-javascript-code-make-you-look-like-a-master-95eaac233545
翻譯 | 楊小愛
Javascript可以做很多神奇的事情,還有很多東西要學(xué)。今天我們介紹13個(gè)簡(jiǎn)短的代碼片段。
1、獲取隨機(jī)布爾值(真/假)
使用 Math.random() 會(huì)返回一個(gè)從 0 到 1 的隨機(jī)數(shù),然后,判斷它是否大于 0.5,你會(huì)得到一個(gè)有 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、反轉(zhuǎn)字符串
反轉(zhuǎn)字符串的方法有很多,這里是最簡(jiǎn)單的一種,使用 split()、reverse() 和 join()
const reverse = str => str.split(‘’).reverse().join(‘’);reverse(‘hello world’);// Result:’dlrow olleh’
4、判斷當(dāng)前標(biāo)簽是否可見
瀏覽器可以打開很多標(biāo)簽,下面的代碼片段是判斷當(dāng)前標(biāo)簽是否為活動(dòng)標(biāo)簽。
const isBrowserTabInView = () => document.hidden;isBrowserTabInView();
5、判斷數(shù)字是奇數(shù)還是偶數(shù)
模數(shù)運(yùn)算符 % 可以很好地完成這個(gè)任務(wù)。
const isEven = num => num% 2 === 0;console.log(isEven(2));// Result: trueconsole.log(isEven(3));// Result: false
6、從Date對(duì)象中獲取時(shí)間
使用Date對(duì)象的.toTimeString()方法轉(zhuǎn)換為時(shí)間字符串,然后截取該字符串。
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、保留指定的小數(shù)位
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);// ExamplestoFixed(25.198726354, 1); // 25.1toFixed(25.198726354, 2); // 25.19toFixed(25.198726354, 3); // 25.198toFixed(25.198726354, 4); // 25.1987toFixed(25.198726354, 5); // 25.19872toFixed(25.198726354, 6); // 25.198726
8、檢查指定元素是否在焦點(diǎn)上
您可以使用 document.activeElement 來確定元素是否處于焦點(diǎn)中。
const elementIsInFocus = (el) => (el === document.activeElement);elementIsInFocus(anyElement)// Result: If it is in focus, it will return True, otherwise it will return False
9、檢查當(dāng)前用戶是否支持觸摸事件
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、檢查當(dāng)前用戶是否為蘋果設(shè)備
可以使用 navigator.platform 來判斷當(dāng)前用戶是否是蘋果設(shè)備。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);// Result: Apple device will return True
11、滾動(dòng)到頁(yè)面頂部
window.scrollTo() 會(huì)滾動(dòng)到指定坐標(biāo),如果坐標(biāo)設(shè)置為(0, 0),會(huì)返回到頁(yè)面頂部。
const goToTop = () => window.scrollTo(0, 0);goToTop();// Result: will scroll to the top
12、獲取所有參數(shù)的平均值
您可以使用 reduce() 函數(shù)計(jì)算所有參數(shù)的平均值。
const average = (…args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);// Result: 2.5
13、轉(zhuǎn)換華氏/攝氏度
不再怕處理溫度單位,下面兩個(gè)函數(shù)就是兩個(gè)溫度單位的相互轉(zhuǎn)換。
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;const fahrenheitToCelsius = (fahrenheit) => (fahrenheit-32) * 5/9;// ExamplescelsiusToFahrenheit(15); // 59celsiusToFahrenheit(0); // 32celsiusToFahrenheit(-20); // -4fahrenheitToCelsius(59); // 15
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

