当前位置: 首页 > news >正文

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));
}

相关文章:

  • 并发编程中的原子性,可见性,有序性问题
  • MySQL的条件判断函数
  • L1-058 6翻了 (15 分)-PAT 团体程序设计天梯赛 GPLT
  • Tomcat I/O 组件——NioEndpoint 再深入
  • 【牛客网刷题】VL8-VL10 generate for语句、比较数大小、function的使用
  • 改进YOLOv7系列:首发最新结合多种X-Transformer结构新增小目标检测层,让YOLO目标检测任务中的小目标无处遁形
  • 外包干了三年,真废了。。。
  • NC57 反转数字
  • Day14-尚品汇-个人中心二级路由搭建
  • 【第一阶段:java基础】第2章:java变量
  • 【Spring】一文带你吃透基于注解的DI技术
  • 跨域(cors和jsonp)
  • 手撕前端面试题【javascript~ 总成绩排名、子字符串频次统计、继承、判断斐波那契数组等】
  • Linux运维面试题总结—Linux基础、计算机网络基础
  • 【小程序websocket前后端交互】uniapp写微信小程序聊天功能功能,websocket交互功能,心跳重连【详细注释,复制即用】
  • 四线法与电桥
  • Linux文件属性与权限
  • 潘功胜:央行将设立5000亿元服务消费与养老再贷款
  • 湖北十堰市委副秘书长管聪履新丹江口市代市长
  • 有人悬赏十万寻找“全国仅剩1只”的斑鳖,发帖者回应并证实
  • 市场监管总局通报民用“三表”专项检查结果
  • 台湾花莲县海域发生5.7级地震,震源深度15公里
  • 福建两名厅级干部履新,张文胜已任省委省直机关工委副书记