导语:
最近在写代码的过程中,在处理一些数据的时候,需要自己去封装一些数据处理的方法,但是如果下次遇到的时候,难免又会去,写相同的代码,所以我就打算把一些常用的封装处理函数,给整理出来,方便下次使用的时候再去定义,这里面的内容,来源有我自己定义的,也有很多好的封装函数是来源的周边文档,觉得不错,所以我也一并整理出来了。
欢迎刷到当前博客的,各路道友,如有更好的,以及其他的一些封装方法,评论或私信分享,本博客会在后续不定期更新,供大家参考学习!
1.生成随机颜色
//方法一
function getRandomColor() { //随机颜色
return `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
}
//方法二
function generateRandomColor() {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
let randomColor=generateRandomColor();//"#F10531"
//方法三
let r = () => Math.random() * 256 >> 0;
let color = `rgb(${r()}, ${r()}, ${r()})`;
//方法四
let randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
2.日常经常使用结构赋值,一般都是先结构,再赋值,这里一行代码实现解构加赋值
let people = { name: null, age: null, Gender: null };
let result = { name: '张三', age: 16, Gender: "男" };
({ name: people.name, age: people.age, Gender: people.Gender } = result);
console.log(people) //{name: '张三', age: 16, Gender: '男'}
3.对基础数据类型进行解构
let { length: a } = '72694';
console.log(a) // 5
4.对数组解构快速拿到某一项值(对数组结构时,可以拿到 length 属性,围绕 length 对数据处理)
let arr = [5, 1, 7, 9, 14];
let { 3: first, length, [length - 1]: last } = arr;
console.log(first);//9
console.log(length);//5
console.log(last);//14
5.将对应下标转为中文零一二三…
function transfromNumber(number) {
const INDEX_MAP = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
if (!number) return
if (number === 10) return INDEX_MAP[number]
return [...number.toString()].reduce((pre, cur) => pre + INDEX_MAP[cur],'')}
console.log(transfromNumber(1234567890)); //一二三四五六七八九零
6.判断参数是否为整数
//方法一
//1.任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。但是对字符串不准确
function isInteger(obj) {
return obj % 1 === 0
}
console.log(isInteger(2)); //true
console.log(isInteger(2.4)); //false
//方法二 添加一个类型判断
function isInteger(obj) {
return typeof obj === 'number' && obj % 1 === 0
}
console.log(isInteger(3)); //true
console.log(isInteger(2.5)); //false
//方法三 使用Math.round、Math.ceil、Math.floor判断 整数取整后还是等于自己。利用这个特性来判断是否是整数
function isInteger(obj) {
return Math.floor(obj) === obj
}
console.log(isInteger(7)); //true
console.log(isInteger(6.5)); //false
//方法四 通过位运算符
function isInteger(obj) {
return (obj | 0) === obj
}
console.log(isInteger(7.7)); //false
console.log(isInteger(6)); //true
//方法五 ES6 提供 Number.isInteger() 方法
function isInteger(obj) {
return Number.isInteger(obj)
}
console.log(isInteger(7.1)); //false
console.log(isInteger(9)); //true
//方法六 isInteger 可解析字符串 ,某些场景不准确
function isInteger(obj) {
return parseInt(obj, 10) === obj
}
7.对数组进行乱序处理
/**
*
* @param {Array<T>} ArrayList
* @param {{ isnewAray: boolean }} isreturnNewArray @接收一个配置对象 @用来指定是否需要不改变源数组 @而返回一个处理后的全新对象
* @returns {T[] | {SourceArray: T[];NewArray: T[];}} @将传入的数组进行乱序处理后返回
*/
export const ArrayRandomOrder = <T>(
ArrayList: Array<T>,
isreturnNewArray: { isnewAray: boolean } = { isnewAray: false }
):
| T[]
| {
SourceArray: T[];
NewArray: T[];
} => {
if (Array.isArray(ArrayList)) {
if (ArrayList.length >= 2) {
if (isreturnNewArray.isnewAray) {
const newArr = [...ArrayList];
for (let i = newArr.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[randomIndex]] = [newArr[randomIndex], newArr[i]];
}
return {
SourceArray: ArrayList,
NewArray: newArr,
};
} else {
for (let i = ArrayList.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1));
[ArrayList[i], ArrayList[randomIndex]] = [ArrayList[randomIndex], ArrayList[i]];
}
return ArrayList;
}
} else {
console.warn(ArrayList, `参数的下标索引长度必须 >= 2 位及以上,请检查传入的参数`);
return ArrayList;
}
} else {
console.error(ArrayList, '参数类型解析错误,应接收一个类型为 Array 的参数');
return ArrayList;
}
};
8.把数组第一项放到最后一项
let a = [1, 2, 3, 4, 5];
function randomBool(arr) {
return arr.push(arr.shift());
}
randomBool(a)
console.log(a); //[2, 3, 4, 5, 1]
//反之 把数组最后一项移到第一项
let a = [1, 2, 3, 4, 5];
function randomBool(arr) {
return arr.unshift(arr.pop());
}
randomBool(a)
console.log(a); //[5, 1, 2, 3, 4]
9.Dom节点平滑滚动到可是区域,顶部,底部
function scrollTo(element) {
element.scrollIntoView({ behavior: "smooth", block: "start" }) // 顶部
element.scrollIntoView({ behavior: "smooth", block: "end" }) // 底部
element.scrollIntoView({ behavior: "smooth"}) // 可视区域
}
10.取出数组中number的 最大值
let arr = [25, 7, 120, 40, 56];
console.log(Math.max(...arr));//120
console.log(Math.min(...arr)); //7
11.检测是否为空对象:(注:无法检测null)
function isEmpty(obj) {
return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
}
12.克隆数组
let arr = [25, 7.145, 7.2, 120, 40, 56];
const clone = (arr) => arr.slice(0);
const clone = (arr) => [...arr];
const clone = (arr) => Array.from(arr);
const clone = (arr) => arr.map((x) => x);
const clone = (arr) => JSON.parse(JSON.stringify(arr));
const clone = (arr) => arr.concat([]);
const clone = (arr) => structuredClone(arr);
13.Boolean转换,(一些场景下我们会将boolean值定义为场景,但是在js中非空的字符串都会被认为是true)
function toBoolean(value, truthyValues = ["true"]) {
const normalizedValue = String(value).toLowerCase().trim();
return truthyValues.includes(normalizedValue);
}
console.log(toBoolean("TRUE")); // true
console.log(toBoolean("FALSE")); // false
console.log(toBoolean("YES", ["yes"])); // true
14.获取年,月,日,时,分,秒,毫秒
获取时间
function extract(date){
const d = new Date(new Date(date).getTime() + 8*3600*1000);
return new Date(d).toISOString().split(/[^0-9]/).slice(0, -1);
}
console.log(extract(new Date())) // ['2022', '09', '19', '18', '06', '11', '187']
15.判断传入参数是否为一个函数
function isFunction(v){
return ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));
}
16.计算两个坐标之间的的距离
function distance(p1, p2){
return `Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
17.通过坐标检测两个dom节点是否覆盖重叠(有些场景下我们需要判断dom是否发生碰撞了或者重叠了,我们可以通过getBoundingClientRect获取到dom的x1,y1,x2,y2坐标然后进行坐标比对即可判断出来)
function overlaps = (a, b) {
return (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
}
18.检测当前开发环境是否为 node 环境
function isNode(){
return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}
19.检测当前浏览器环境是否处于断网状态
if (window.navigator.onLine) {
console.log("在线");
} else {
console.log("离线");
}
window.addEventListener("offline", (e) => { //初始化不执行,网络状态改变时会触发执行
console.log("网络已断开!", e);
})
window.addEventListener("online", (e) => {
console.log("网络已重新连接", e);
})
20.循环切换浏览器 全屏
/**
* @封装切换浏览器全屏事件API
*/
/**
* @param {HTMLElement} elment 接收一个要切换到全屏的元素调用进入全屏的方法
*/
export const enterFullScreen = (elment: HTMLElement): void => {
if (elment.requestFullscreen) {
elment.requestFullscreen();
} else if (elment.mozRequestFullScreen) {
elment.mozRequestFullScreen();
} else if (elment.webkitRequestFullscreen) {
elment.webkitRequestFullscreen();
} else if (elment.msRequestFullScreen) {
elment.msRequestFullScreen();
} else {
alert('抱歉!你当前浏览器不支持全屏切换功能!请尝试更换浏览器');
}
};
/** @退出全屏 */
export const exitFullScreen = (): void => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else {
alert('抱歉!你当前浏览器不支持退出全屏功能!请尝试更换浏览器操作');
}
};
/**
* @returns 得到当前处于全屏的元素
*/
export const isElment = (): HTMLElement | null => {
return (
document.fullscreenElement ||
document.mozfullscreenElement ||
document.msfullscreenElement ||
document.webkitfullscreenElement ||
null
);
};
/**
* @returns 获取当前是否已经处于全屏状态
*/
export const isFull = (): boolean => {
return !isElment();
};
/**
* @param {HTMLElement}elment 接收一个要切换到全屏的元素
*/
export const toggle = (elment: typeof document.documentElement | HTMLElement = document.documentElement): void => {
isFull() ? enterFullScreen(elment) : exitFullScreen();
};
21. 截取 URL 路径参数
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substring(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
}
// http://localhost/jtopo_topology-master/network_topology.html?sysId=67
console.log(GetQueryString('ticket')); // 返回值 67
22.禁用浏览器屏幕缩放
// 禁用浏览器屏幕缩放
window.addEventListener('mousewheel', (event) => {
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault()
}
}, { passive: false });
//firefox 禁用屏幕缩放
window.addEventListener('DOMMouseScroll', (event) => {
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault()
}
}, { passive: false });
🚵♂️ 博主座右铭:向阳而生,我还在路上!
——————————————————————————————
🚴博主想说:将持续性为社区输出自己的资源,同时也见证自己的进步!
——————————————————————————————
🤼♂️ 如果都看到这了,博主希望留下你的足迹!【📂收藏!👍点赞!✍️评论!】
——————————————————————————————