一行 JavaScript 代碼搞定這些騷操作!收藏了~
JavaScript 是一門神奇的語(yǔ)言,它的某些特性讓人捉摸不透,但其簡(jiǎn)潔和靈活性也讓人愛不釋手。
有些功能邏輯按常規(guī)思路可能需要不少代碼,但是利用某些 API 和語(yǔ)法特性,短短一行代碼就能完成!本文簡(jiǎn)單列舉一些常用的一行代碼,希望對(duì)你有用。
1. 獲取隨機(jī)布爾值 (true/false)
Math.random()會(huì)返回 0 到1之間隨機(jī)的數(shù)字,因此可以利用返回值是否比 0.5小來返回隨機(jī)的布爾值。
const?randomBoolean?=?()?=>?Math.random()?>=?0.5;
console.log(randomBoolean());
2. 反轉(zhuǎn)字符串
結(jié)合數(shù)組的反轉(zhuǎn)方法,可以反轉(zhuǎn)字符串:
const?reverse?=?str?=>?str.split('').reverse().join('');
reverse('hello?world');?????
//?Result:?'dlrow?olleh'
3. 數(shù)組去重
面試常考題,偷懶的做法就是用Set。
let?removeDuplicates?=?arr?=>?[...new?Set(arr)];
console.log(removeDuplicates(['foo',?'bar',?'bar',?'foo',?'bar']));
?//?['foo',?'bar']
4. 判斷瀏覽器 Tab 窗口是否為活動(dòng)窗口
利用document.hidden屬性可以判斷瀏覽器窗口是否可見(當(dāng)前活動(dòng)窗口)。
const?isBrowserTabInView?=?()?=>?document.hidden;
isBrowserTabInView();
5. 判斷數(shù)字奇偶
小學(xué)數(shù)學(xué)題,用% 2判斷就行:
const?isEven?=?num?=>?num?%?2?===?0;
console.log(isEven(2));
//?Result:?true
console.log(isEven(3));
//?Result:?false
6. 獲取日期對(duì)象的時(shí)間部分
日期對(duì)象的?.toTimeString()方法可以獲取時(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:?will?log?the?current?time
7. 數(shù)字截?cái)嘈?shù)位
如果需要截?cái)喔↑c(diǎn)數(shù)的小數(shù)位(不是四舍五入),可以借助?Math.pow()?實(shí)現(xiàn):
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. 判斷 DOM 元素是否已獲得焦點(diǎn)
const?elementIsInFocus?=?(el)?=>?(el?===?document.activeElement);
elementIsInFocus(anyElement)
9. 判斷當(dāng)前環(huán)境是否支持 touch 事件
const?touchSupported?=?()?=>?{
??('ontouchstart'?in?window?||?window.DocumentTouch?&&?document?instanceof?window.DocumentTouch);
}
console.log(touchSupported());
10. 判斷是否為 Apple 設(shè)備
const?isAppleDevice?=?/Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
11. 滾動(dòng)到頁(yè)面頂部
window.scrollTo()?方法接受x和y坐標(biāo)參數(shù),用于指定滾動(dòng)目標(biāo)位置。全都設(shè)置為 0,可以回到頁(yè)面頂部。注意:IE 不支持 .scrollTo()方法。
const?goToTop?=?()?=>?window.scrollTo(0,?0);
goToTop();
12. 求平均值
reduce的典型應(yīng)用場(chǎng)景:數(shù)組求和。
const?average?=?(...args)?=>?args.reduce((a,?b)?=>?a?+?b)?/?args.length;
average(1,?2,?3,?4);
//?Result:?2.5
最后,給大家推薦一款Cocos Store最新特效資源『卡通風(fēng)格水面渲染特效』,還有玉兔小組組的視頻講解哦!


評(píng)論
圖片
表情
