JavaScript---常用JS方法(utils.js)额外篇
目录
1. 一行代码完成解构加赋值(解构赋值新解)
2. 判断整数的不同方法
3. 通过css检测系统的主题色从而全局修改样式
4. 数组随机打乱顺序
5. 随机获取一个Boolean值
6. 把数组的第一项放到最后一项
7. dom节点平滑滚动到可是区域,顶部,底部
8. 获取随机颜色
9. 检测是否为空对象
10. 数组克隆方法总结(clone)
11. 一步从时间中提取年月日时分秒(推荐使用)
12. 检测两个dom节点是否覆盖重叠
13. 判断是否是NodeJs环境
14. 参数求和和参数平均数
15. 计算两个坐标之间的距离
1. 一行代码完成解构加赋值(解构赋值新解)
// 对于结构赋值,平时都是解构后或者起别名的方式获取
// 而后采用变量赋值的形式去储存新的变量,如下:
let params = {}; // 需要储存的最终对象
let obj = {a:1,b:2,c:3}
// 1. 常规解构获取
let {a, b:other} = obj; // console.log(a,other)
params = {a,other} // console.log(params)
// 2. 直接赋值的改动(推荐写法)
let { a: params.a, b:params.other } = obj // console.log(params)
举例其他情况:
1. 字符串的结构
const {length : a} = '1234';
console.log(a) // 4
2. 数组解构快速拿到最后一项值
const arr = [1, 2, 3];
const { 0: first, length, [length - 1]: last } = arr;
first; // 1
last; // 3
length; // 3
2. 判断整数的不同方法
// 1. 任何整数除以1,余数为0
function isInteger(obj) {
return typeof obj === 'number' && obj%1 === 0
}
// 2. 使用Math.round、Math.ceil、Math.floor判断 整数取整后还是等于自己。
// 利用这个特性来判断是否是整数
function isInteger(obj) {
// Math.round | Math.floor 也可以哦
return Math.floor(obj) == obj
}
// 3. 通过位运算符取整判断
function isInteger(obj) {
return (obj | 0) == obj
}
// 4. ES6提供了Number.isInteger
function isInteger(obj) {
return typeof obj === 'number' && Number.isInteger(obj)
}
3. 通过css检测系统的主题色从而全局修改样式
// @media 的属性 prefers-color-scheme就可以知道当前的系统主题,当然使用前需要查查兼容性
@media (prefers-color-scheme: dark) { //... }
@media (prefers-color-scheme: light) { //... }
// javascript写法控制
window.addEventListener('theme-mode', event =>{
if(event.mode == 'dark'){}
if(event.mode == 'light'){}
})
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
if (event.matches) {} // dark mode
})
4. 数组随机打乱顺序
// 洗牌算法打乱数组顺序
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1))
;[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]
}
return arr
}
5. 随机获取一个Boolean值
// Math.random() 的区间是0-0.99
function randomBoolean() {
return 0.5 - Math.random()
}
6. 把数组的第一项放到最后一项
function arrpushfirst(arr){
return arr.unshift(arr.pop());
}
[3, 6, 1, 2, 4, 5, 7] ==> [7, 3, 6, 1, 2, 4, 5]
7. dom节点平滑滚动到可是区域,顶部,底部
function scrollTo(element) {
// 三个位置,自行选择使用
element.scrollIntoView({ behavior: "smooth", block: "start" }) // 顶部
element.scrollIntoView({ behavior: "smooth", block: "end" }) // 底部
element.scrollIntoView({ behavior: "smooth"}) // 可视区域
}
8. 获取随机颜色
// 日常我们经常会需要获取一个随机颜色,通过随机数即可完成
function getRandomColor(){
return `#${Math.floor(Math.random() * 0xffffff) .toString(16)}`;
}
9. 检测是否为空对象
// 通过使用Es6的Reflect静态方法判断他的长度依次判断是否是空数组,
// 也可以通过Object.keys()来判断
function isEmpty(obj){
return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
}
10. 数组克隆方法总结(clone)
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);
11. 一步从时间中提取年月日时分秒(推荐使用)
// 一步获取到年月日时分秒毫秒,由于toISOString会丢失时区,导致时间差八小时
// 所以在格式化之前我们加上八个小时时间即可
function extract(date){
date = date ? new Date(date) : new Date()
const d = new Date(date.getTime() + 8*3600*1000);
return new Date(d).toISOString().split(/[^0-9]/).slice(0, -1);
}
console.log(extract(new Date())) // ['2022', '10', '26', '17', '18', '58', '256']
12. 检测两个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);
}
13. 判断是否是NodeJs环境
// 通过判断全局环境来检测是否是nodeJs环境
function isNode(){
return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}
14. 参数求和和参数平均数
// 通过reduce一行即可
function sum(...args){
args.reduce((a, b) => a + b);
}
// 求平均数
function sum(...args){
args.reduce((a, b) => a + b) / args.length;
}
15. 计算两个坐标之间的距离
function distance(p1, p2){
return `Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}