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