
英文 | https://javascript.plainenglish.io/20-simple-but-useful-javascript-coding-techniques-that-you-should-use-23f33bd45325
1.滾動到頁面頂部
我們可以使用 window.scrollTo() 平滑滾動到頁面頂部。
const scrollToTop = () => {
window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};
2.滾動到頁面底部
當然,如果知道頁面的高度,也可以平滑滾動到頁面底部。
const scrollToBottom = () => {
window.scrollTo({
top: document.documentElement.offsetHeight,
left: 0,
behavior: "smooth",
});
};
3.滾動元素到可見區域
有時我們需要将元素滾動到可見區域,我們應該怎麼做?使用 scrollIntoView 就足夠了。
const smoothScroll = (element) => {
element.scrollIntoView({
behavior: "smooth",
});
};
4.全屏顯示元素
你一定遇到過這樣的場景,需要全屏播放視訊,并在浏覽器中全屏打開頁面。
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.退出浏覽器全屏狀态
是的,這個和第4點一起使用,你也會有退出浏覽器全屏狀态的場景。
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.擷取資料類型
如何通過函數擷取變量的資料類型?
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.停止冒泡事件
一種适用于所有平台的防止事件冒泡的方法。
const stopPropagation = (event) => {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};
8. 深拷貝一個對象
如何複制深度嵌套的對象?
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. 确定裝置類型
我們經常必須這樣做才能在手機上顯示 A 邏輯,在 PC 上顯示 B 邏輯。基本上,裝置類型是通過識别浏覽器的 userAgent 來确定的。
const isMobile = () => {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
);
};
10.判斷裝置是安卓還是IOS
除了區分是移動端還是PC端,很多時候我們還需要區分目前裝置是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.擷取浏覽器類型及其版本
作為前端開發人員,您可能會遇到各種相容性問題,這時候可能需要擷取浏覽器的類型和版本。
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.設定cookies
cookie 可能是我見過的最糟糕的 API,它很難使用,以至于我們不得不重新封裝它以最大限度地提高開發效率。
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 的想法是什麼?其實,隻要把它的過期時間設定為這一刻,它就會立即過期。
const delCookie = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`;
};
15.生成随機字元串
不知道大家有沒有遇到過需要生成随機字元串的場景。我遇到過很多次,每次都要google一遍,直到學會這個工具功能。
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.生成指定範圍内的随機數
也許出于測試目的,我經常需要生成一定範圍内的随機數。
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6
randomNum(10, 20) // 11
18.打亂數組的順序
如何打亂數組的原始順序?
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. 從數組中擷取随機值
之前做過一個抽獎項目,需要讓數組中的獎品随機出現。
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'
第二種方式
正規表達式讓我們很頭疼,不是嗎?是以我們需要找到一種更簡單的方式來格式化貨币。
const formatMoney = (money) => {
return money.toLocaleString()
}
formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'
我太喜歡這種方式了,簡單易懂。
總結
以上就是我今天跟你分享的20個關于JavaScript技術簡單實用的技巧,希望你能夠從中學到新的知識。如果你覺得有用的話,請記得點贊我,關注我,并将其分享給你身邊的朋友,也許能夠幫助到他。
最後,感謝你的閱讀,祝程式設計愉快。