20個(gè)既簡(jiǎn)單又實(shí)用的JavaScript小技巧
1.滾動(dòng)到頁面頂部
我們可以使用 window.scrollTo() 平滑滾動(dòng)到頁面頂部。
?
?
const?scrollToTop?=?()?=>?{
??window.scrollTo({?top:?0,?left:?0,?behavior:?"smooth"?});
};
?
2.滾動(dòng)到頁面底部
當(dāng)然,如果知道頁面的高度,也可以平滑滾動(dòng)到頁面底部。
?
?
const?scrollToBottom?=?()?=>?{
??window.scrollTo({
????top:?document.documentElement.offsetHeight,
????left:?0,
????behavior:?"smooth",
??});
};
?
3.滾動(dòng)元素到可見區(qū)域
有時(shí)我們需要將元素滾動(dòng)到可見區(qū)域,我們應(yīng)該怎么做?使用 scrollIntoView 就足夠了。
?
?
const?smoothScroll?=?(element)?=>?{
??element.scrollIntoView({
????behavior:?"smooth",
??});
};
?
4.全屏顯示元素
你一定遇到過這樣的場(chǎng)景,需要全屏播放視頻,并在瀏覽器中全屏打開頁面。
?
?
const?goToFullScreen?=?(element)?=>?{
??element?=?element?||?document.body;
??if?(element.requestFullscreen)?{
????element.requestFullscreen();
??}?else?if?(element.mozRequestFullScreen)?{
????element.mozRequestFullScreen();
??}?else?if?(element.msRequestFullscreen)?{
????element.msRequestFullscreen();
??}?else?if?(element.webkitRequestFullscreen)?{
????element.webkitRequestFullScreen();
??}
};
?
5.退出瀏覽器全屏狀態(tài)
是的,這個(gè)和第4點(diǎn)一起使用,你也會(huì)有退出瀏覽器全屏狀態(tài)的場(chǎng)景。
?
?
const?goExitFullscreen?=?()?=>?{
??if?(document.exitFullscreen)?{
????document.exitFullscreen();
??}?else?if?(document.msExitFullscreen)?{
????document.msExitFullscreen();
??}?else?if?(document.mozCancelFullScreen)?{
????document.mozCancelFullScreen();
??}?else?if?(document.webkitExitFullscreen)?{
????document.webkitExitFullscreen();
??}
};
?
6.獲取數(shù)據(jù)類型
如何通過函數(shù)獲取變量的數(shù)據(jù)類型?
?
?
const?getType?=?(value)?=>?{
??const?match?=?Object.prototype.toString.call(value).match(/?(\w+)]/)
??return?match[1].toLocaleLowerCase()
}
getType()?//?undefined
getType({}})?//?object
getType([])?//?array
getType(1)?//?number
getType('fatfish')?//?string
getType(true)?//?boolean
getType(/fatfish/)?//?regexp
?
7.停止冒泡事件
一種適用于所有平臺(tái)的防止事件冒泡的方法。
?
?
const?stopPropagation?=?(event)?=>?{
??event?=?event?||?window.event;
??if?(event.stopPropagation)?{
????event.stopPropagation();
??}?else?{
????event.cancelBubble?=?true;
??}
};
?
8.??深拷貝一個(gè)對(duì)象
如何復(fù)制深度嵌套的對(duì)象?
?
?
const?deepCopy?=?(obj,?hash?=?new?WeakMap())?=>?{
??if?(obj?instanceof?Date)?{
????return?new?Date(obj);
??}
??if?(obj?instanceof?RegExp)?{
????return?new?RegExp(obj);
??}
??if?(hash.has(obj))?{
????return?hash.get(obj);
??}
??let?allDesc?=?Object.getOwnPropertyDescriptors(obj);
??let?cloneObj?=?Object.create(Object.getPrototypeOf(obj),?allDesc);
??hash.set(obj,?cloneObj);
??for?(let?key?of?Reflect.ownKeys(obj))?{
????if?(obj[key]?&&?typeof?obj[key]?===?"object")?{
??????cloneObj[key]?=?deepCopy(obj[key],?hash);
????}?else?{
??????cloneObj[key]?=?obj[key];
????}
??}
??return?cloneObj;
};
?
9.??確定設(shè)備類型
我們經(jīng)常必須這樣做才能在手機(jī)上顯示 A 邏輯,在 PC 上顯示 B 邏輯?;旧?,設(shè)備類型是通過識(shí)別瀏覽器的 userAgent 來確定的。
?
?
const?isMobile?=?()?=>?{
??return?!!navigator.userAgent.match(
????/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows?Phone|Phone)/i
??);
};
?
10.判斷設(shè)備是安卓還是IOS
除了區(qū)分是移動(dòng)端還是PC端,很多時(shí)候我們還需要區(qū)分當(dāng)前設(shè)備是Android還是IOS。
?
?
const?isAndroid?=?()?=>?{
??return?/android/i.test(navigator.userAgent.toLowerCase());
};
const?isIOS?=?()?=>?{
??let?reg?=?/iPhone|iPad|iPod|iOS|Macintosh/i;
??return?reg.test(navigator.userAgent.toLowerCase());
};
?
11.獲取瀏覽器類型及其版本
作為前端開發(fā)人員,您可能會(huì)遇到各種兼容性問題,這時(shí)候可能需要獲取瀏覽器的類型和版本。
?
?
const?getExplorerInfo?=?()?=>?{
??let?t?=?navigator.userAgent.toLowerCase();
??return?0?<=?t.indexOf("msie")
??????{
????????//ie?<?11
????????type:?"IE",
????????version:?Number(t.match(/msie?([\d]+)/)[1]),
??????}
????:?!!t.match(/trident\/.+?rv:(([\d.]+))/)
??????{
????????//?ie?11
????????type:?"IE",
????????version:?11,
??????}
????:?0?<=?t.indexOf("edge")
??????{
????????type:?"Edge",
????????version:?Number(t.match(/edge\/([\d]+)/)[1]),
??????}
????:?0?<=?t.indexOf("firefox")
??????{
????????type:?"Firefox",
????????version:?Number(t.match(/firefox\/([\d]+)/)[1]),
??????}
????:?0?<=?t.indexOf("chrome")
??????{
????????type:?"Chrome",
????????version:?Number(t.match(/chrome\/([\d]+)/)[1]),
??????}
????:?0?<=?t.indexOf("opera")
??????{
????????type:?"Opera",
????????version:?Number(t.match(/opera.([\d]+)/)[1]),
??????}
????:?0?<=?t.indexOf("Safari")
??????{
????????type:?"Safari",
????????version:?Number(t.match(/version\/([\d]+)/)[1]),
??????}
????:?{
????????type:?t,
????????version:?-1,
??????};
};
?
12.設(shè)置cookies
cookie 可能是我見過的最糟糕的 API,它很難使用,以至于我們不得不重新封裝它以最大限度地提高開發(fā)效率。
?
?
const?setCookie?=?(key,?value,?expire)?=>?{
??const?d?=?new?Date();
??d.setDate(d.getDate()?+?expire);
??document.cookie?=?`${key}=${value};expires=${d.toUTCString()}`;
};
?
13.??獲取 cookie
除了寫入 cookie 之外,我們還將參與其讀取操作。
?
?
const?getCookie?=?(key)?=>?{
??const?cookieStr?=?unescape(document.cookie);
??const?arr?=?cookieStr.split(";?");
??let?cookieValue?=?"";
??for?(let?i?=?0;?i?<?arr.length;?i++)?{
????const?temp?=?arr[i].split("=");
????if?(temp[0]?===?key)?{
??????cookieValue?=?temp[1];
??????break;
????}
??}
??return?cookieValue;
};
?
14.刪除cookies
刪除 cookie 的想法是什么?其實(shí),只要把它的過期時(shí)間設(shè)置為這一刻,它就會(huì)立即過期。
?
?
const?delCookie?=?(key)?=>?{
??document.cookie?=?`${encodeURIComponent(key)}=;expires=${new?Date()}`;
};
?
15.生成隨機(jī)字符串
不知道大家有沒有遇到過需要生成隨機(jī)字符串的場(chǎng)景。我遇到過很多次,每次都要google一遍,直到學(xué)會(huì)這個(gè)工具功能。
?
?
const?randomString?=?(len)?=>?{
??let?chars?=?"ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
??let?strLen?=?chars.length;
??let?randomStr?=?"";
??for?(let?i?=?0;?i?<?len;?i++)?{
????randomStr?+=?chars.charAt(Math.floor(Math.random()?*?strLen));
??}
??return?randomStr;
};
randomString(10)?//?pfkMfjEJ6x
randomString(20)?//?ce6tEx1km4idRNMtym2S
?
16.??字符串首字母大寫
?
?
const?fistLetterUpper?=?(str)?=>?{
??return?str.charAt(0).toUpperCase()?+?str.slice(1);
};
fistLetterUpper('fatfish')?//?Fatfish
?
17.生成指定范圍內(nèi)的隨機(jī)數(shù)
也許出于測(cè)試目的,我經(jīng)常需要生成一定范圍內(nèi)的隨機(jī)數(shù)。
?
?
const?randomNum?=?(min,?max)?=>?Math.floor(Math.random()?*?(max?-?min?+?1))?+?min;
randomNum(1,?10)?//?6
randomNum(10,?20)?//?11
?
18.打亂數(shù)組的順序
如何打亂數(shù)組的原始順序?
?
?
const?shuffleArray?=?(array)?=>?{
??return?array.sort(()?=>?0.5?-?Math.random())
}
let?arr?=?[?1,?-1,?10,?5?]
shuffleArray(arr)?//?[5,?-1,?10,?1]
shuffleArray(arr)?//?[1,?10,?-1,?5]
?
19.??從數(shù)組中獲取隨機(jī)值
之前做過一個(gè)抽獎(jiǎng)項(xiàng)目,需要讓數(shù)組中的獎(jiǎng)品隨機(jī)出現(xiàn)。
?
?
const?getRandomValue?=?array?=>?array[Math.floor(Math.random()?*?array.length)];?
const?prizes?=?[??'$100',?'??',?'??'?]
getRandomValue(prizes)?//???
getRandomValue(prizes)?//???
getRandomValue(prizes)?//???
?
20.??格式化貨幣
格式化貨幣的方式有很多,比如這兩種方式。
第一種方法
?
?
const?formatMoney?=?(money)?=>?{
??return?money.replace(new?RegExp(`(?!^)(?=(\\d{3})+${money.includes('.')???'\\.'?:?'$'})`,?'g'),?',')??
}
formatMoney('123456789')?//?'123,456,789'
formatMoney('123456789.123')?//?'123,456,789.123'
formatMoney('123')?//?'123'
?
第二種方式
正則表達(dá)式讓我們很頭疼,不是嗎?所以我們需要找到一種更簡(jiǎn)單的方式來格式化貨幣。
?
?
const?formatMoney?=?(money)?=>?{
鏈接:https://www.dianjilingqu.com/628687.html
??return?money.toLocaleString()
}
formatMoney(123456789)?//?'123,456,789'
formatMoney(123456789.123)?//?'123,456,789.123'
formatMoney(123)?//?'123'