记录一些简单实用的JS代码技巧
1.获取数据类型
封装一个公共函数来获取变量的数据类型
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
2.阻止冒泡事件
适用于所有平台的阻止冒泡事件的公共方法
const stopPropagation = (event) => {event = event || window.event;if (event.stopPropagation) {event.stopPropagation();} else {event.cancelBubble = true;}
};
3.深拷贝对象
深度复制多层嵌套的对象
//第一种
const deepClone=(obj)=>{var objClone = Array.isArray(obj) ? [] : {}if (obj && typeof obj === "object") {for (var key in obj) {// eslint-disable-next-line no-prototype-builtinsif (obj.hasOwnProperty(key)) {if (obj[key] && typeof obj[key] === "object") {objClone[key] = deepClone(obj[key])} else {objClone[key] = obj[key]}}}}return objClone
}
//第一种
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;
};
4.设置cookie值
封装公共的设置cookie值,提高开发效率
const setCookie = (key, value, expire) => {const d = new Date();d.setDate(d.getDate() + expire);document.cookie = `${key}=${value};expires=${d.toUTCString()}`;
};
5.获取cookie值
除了设置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;
};
6.删除cookie
删除cookie其实就是给cookie设置过期时间,超过这个时刻它就会立即过期
const delCookie = (key) => {document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`;
};
7.生成随机字符串
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
8.从数组中获取一个随机值
类似抽奖,出现一个随机结果
const getRandomValue = array => array[Math.floor(Math.random() * array.length)];
const prizes = [ '$100', '🍫', '🍔','1234' ]getRandomValue(prizes) // 🍫
getRandomValue(prizes) // 🍔
getRandomValue(prizes) // 🍫
9.随机生成指定范围内的数值
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6
randomNum(10, 20) // 11
10.将字符串的首字母变成大写
const fistLetterUpper = (str) => {return str.charAt(0).toUpperCase() + str.slice(1);
};fistLetterUpper('fish') // Fish
11.一键滚动到页面顶部
const scrollToTop = () => {window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};
12.一键滚动到页面底部
const scrollToBottom = () => {window.scrollTo({top: document.documentElement.offsetHeight,left: 0,behavior: "smooth",});
};
13.将元素滚动到可见区域
使用 scrollIntoView 就可以实现将元素滚动到可见区域
const smoothScroll = (element) => {element.scrollIntoView({behavior: "smooth",});
};
14.全屏显示
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();}
};
15.退出全屏显示
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();}
};
16.判断设备类型
有时候经常会遇到一些在手机端显示逻辑A,在pc端显示逻辑B
const isMobile = () => {return !!navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i);
};
17.判断设备是Android还是IOS
记得有写过一个H5下载页面,安卓和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());
};
18.货比格式化方法
//让人头疼的正则表达式
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'