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

前端常用的方法

时间处理

moment时间处理函数

// 时间日期相关常用的方法变量
import moment from 'moment';// 获取当前时间 moment
export const nowDateMoment = moment(new Date());
export const nowDateY = moment(new Date()).format('YYYY');
export const nowDateM = moment(new Date()).format('MM');
export const nowDateYM = moment(new Date()).format('YYYY-MM');
export const nowDateYMD = moment(new Date()).format('YYYY-MM-DD');
export const nowDateYMDHms = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');// 把年月 转换为 年-月
export const YMFormattedYM = (year: number | string, month: number | string) => {let newMonth = Number(month) > 9 ? month : `0${month}`;return `${dateFormattedY(year)}-${newMonth}`;
};// 日期格式转换为moment
export const dateFormattedMoment = (date: any) => {let newDate = date;if (date && typeof date === 'string') {newDate = moment(date);}return newDate;
};// 格式化时间 YYYY
export const dateFormattedY = (date: any) => {return date ? dateFormattedMoment(date).format('YYYY') : date;
};// 格式化时间 MM
export const dateFormattedM = (date: any) => {return date ? dateFormattedMoment(date).format('MM') : date;
};// 格式化时间 YYYY-MM
export const dateFormattedYM = (date: any) => {return date ? dateFormattedMoment(date).format('YYYY-MM') : date;
};// 格式化时间 YYYY-MM-DD
export const dateFormattedYMD = (date: any) => {return date ? dateFormattedMoment(date).format('YYYY-MM-DD') : date;
};// 格式化时间 YYYY-MM-DD HH:mm:ss
export const dateFormattedYMDHms = (date: any) => {return date ? dateFormattedMoment(date).format('YYYY-MM-DD HH:mm:ss') : date;
};// 格式化时间  YYYY-MM-DDTHH:mm:ss.SSSZ
export const dateFormattedSSSZ = (date: any) => {return date ? dateFormattedMoment(date).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : date;
};// 格式化时间  'YYYY-MM-DDTHH:mm:ss.000+0800  2022-03-24T08:56:36.000+0800
export const dateFormattedTimezone = (date: any) => {return date ? dateFormattedSSSZ(date).slice(0, -3) + '00' : date;
};// 获取本周周几的日期
export const getWeekDate = (day: number) => {// moment().weekday(0).format('YYYY/MM/DD') //本周一// moment().weekday(6).format('YYYY/MM/DD') //本周日return moment().weekday(day).format('YYYYMMDD');
};// 比较两个时间 是否等于
export const isEqDate = (startDate: any, endDate: any) => {return compareDate(startDate, endDate, 'eq');
};// 比较两个时间 是否大于
export const isGtStartDate = (startDate: any, endDate: any) => {return compareDate(startDate, endDate, 'gt');
};// 比较两个时间 是否大于等于
export const isGeStartDate = (startDate: any, endDate: any) => {return compareDate(startDate, endDate, 'ge');
};// 比较两个时间 是否小于
export const isLtEndDate = (startDate: any, endDate: any) => {return compareDate(startDate, endDate, 'lt');
};// 比较两个时间 是否小于等于
export const isLeEndDate = (startDate: any, endDate: any) => {return compareDate(startDate, endDate, 'le');
};// 对时间进行排序
export const isSortDate = (startDate: any, endDate: any) => {return startDate === endDate ? 0 : isGtStartDate(startDate, endDate) ? 1 : -1;
};// 比较时间公共方法
const compareDate = (startDate: any, endDate: any, type: string) => {if (!startDate || !endDate) return false;let newStartDate = dateFormattedYMD(startDate);let newEendDate = dateFormattedYMD(endDate);let condition;switch (type) {case 'eq':condition = newStartDate === newEendDate;break;case 'gt':condition = newStartDate > newEendDate;break;case 'ge':condition = newStartDate >= newEendDate;break;case 'lt':condition = newStartDate < newEendDate;break;case 'le':condition = newStartDate <= newEendDate;break;}return condition ? true : false;
};// 是否在两个日期范围内
export const isDateRange = (startDate: any, endDate: any, date: any) => {let newDate = dateFormattedYMD(date);if (dateFormattedYMD(startDate) <= newDate && newDate <= dateFormattedYMD(endDate)) {return true;}return false;
};// 获取两个日期的差值  2022-03-25  2022-03-20  5天
export const getDiffDays = (endDate: any, startDate: any) => {if (endDate && startDate) {return moment(endDate).diff(moment(startDate), 'day');} else {return 0;}
};// 开始时间增加N天
export const getAddDays = (startDate: any, days: number) => {let newStartDate = dateFormattedMoment(startDate);if (days >= 0) {newStartDate.add(days, 'days');}return newStartDate;
};// 开始时间减N天
export const getSubtractDays = (startDate: any, days: number) => {let newStartDate = dateFormattedMoment(startDate);if (days >= 0) {newStartDate.subtract(days, 'days');}return newStartDate;
};

时间戳处理成为年月日时分秒

  const convertTimestampToHMS=(timestampStr) =>{const timestampdata = Number(timestampStr);var date = new Date(timestampdata);var year = date.getFullYear();var month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1var day = String(date.getDate()).padStart(2, '0');var hours = String(date.getHours()).padStart(2, '0');var minutes = String(date.getMinutes()).padStart(2, '0');var seconds = String(date.getSeconds()).padStart(2, '0');return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;}

将年月日时分秒的数据处理成为时间戳

 function convertDateTimeToTimestamp(dateTimeStr, year = 2024) {const fullDateTimeStr = `${year}-${dateTimeStr}`;const date = new Date(fullDateTimeStr.replace('-', 'T'));const timestamp = date.getTime();return timestamp;}

处理对象的方法对象的属性

遍历对象

//方法1  
let obj = {user: "name",};for (let k in obj) {console.log(k);}
//输出 user
//方法2let a = {1733813940000: [{occurTime: 1733813940000,},],1733814000000: [{occurTime: 1733814000000,},],};Object.keys(a).forEach((key) => {console.log(key);console.log(a[key]);});

对象的浅拷贝

let a={
name:1
};
let b={
type:”Add“
};
Object.assign(a,b)
let obj ={...a,...b}

处理2个数据相同的数据处理类型2个都是对象,且数据完全一致把他筛选出来

function filterDuplicates(arr) {return arr.reduce((acc, current) => {const stringifiedCurrent = JSON.stringify(current);if (!acc.map(JSON.stringify).includes(stringifiedCurrent)) {acc.push(current);}return acc;}, []);}

本地存储

拿到本地存储的对象的方法

   export const getLocalStorageuserInfo = (localName, data) => {const storedUserInfo = localStorage.getItem(localName);if (storedUserInfo) {const parsedUserInfo = JSON.parse(storedUserInfo)[data];return parsedUserInfo;}};

设置本地存储的方法

  export const setLocalStorage = (localName, data) => {localStorage.setItem(localName, JSON.stringify(data));return;};setLocalStorage("data", a);

删除设定的值的本地存储

 const removeLocalStorage = (data) => {localStorage.removeItem(data);return;};

删除所有的本地存储

  const removeTotalLocalStorage = () => {localStorage.clear();return;};

数组处理

将平铺的数组转化为属性结构的数组

const wbsArray = [{id: '1',pid: '0',name: 'Parent'},{id: '2',pid: '1',name: 'Child 1'},{id: '3',pid: '1',name: 'Child 2'}// ...其他数据]function wbsArrayToTree(array, rootId = '0'){let parent = []let children = []array.forEach((item) => {item.pid === rootId ?(parent = [...parent, item]) :(children = [...children, item])})const translator = (parent, children) => {parent.forEach((parent) => {children.forEach((current, index) => {if (current.pid === parent.id) {// const temp = JSON.parse(JSON.stringify(children))const temp = [...children]temp.splice(index, 1)translator([current], temp)typeof parent['children'] !== 'undefined' ?parent.children.push(current) :(parent.children = [current])parent['childIds'] && delete parent['childIds']}})})}translator(parent, children)return parent}const tree = wbsArrayToTree(wbsArray);console.log(tree);

树形数组转为一维数组

//方法1function flattenAndSort(array) {return array.reduce((result, element) => {// 如果元素是数组,则递归调用flattenAndSortif (Array.isArray(element)) {console.log(element, "1");result = result.concat(flattenAndSort(element));} else {result.push(element);}return result;}, []).sort((a, b) => a - b); // 排序数组}const flattenedAndSortedArray = flattenAndSort(arr);console.log(flattenedAndSortedArray, "27");
//方法2function getArry(arr) {const trust= []function fn(arr) {arr.forEach(element => {if (Array.isArray(element)) {fn(element);} else {trust.push(element);}});}fn(arr)return trust.sort((a, b) => a - b)}const trust = getArry(arr)console.log(trust);

当一个需要另一个数组的数据的时候需要怎么样进行处理

 success.forEach((item) => {list.forEach((item1) => {if (item.time !== item1.time) {obj.push({ ...item, type: '有效告警', value: 0 });obj.push({ ...item, type: '无效告警', value: 0 });}});});let uniqueData = filterDuplicates(obj);uniqueData.sort((a, b) => parseInt(a.time1) - parseInt(b.time1));
//这样的使用的时候可能造成的情况就是会导致重复的数据需要借助上方的过滤对象的方法

处理数组的数组的需要判断是否有一个数据是false或者为true来达到自增的目的

 const getValues = (r, v) => {let Noise = 0;v.forEach((item) => {if (!item.ruleAlarmNoise) {// 正确的自增方式Noise++;}});return Noise;};

对字符串进行处理

对 "#### 日均量: 884159.01笔/天\n#### 日均有流量时间占比: 100.00%\n\n#### ><font“处理

 const getNosrt = (value) => {if (!value) return [];let parts = value.split('#');let result = [];parts = parts.filter((part) => part.trim() !== '');for (let part of parts) {result.push(part.trim());}let joinedString = result.join(',');return joinedString;};


http://www.mrgr.cn/news/80065.html

相关文章:

  • 【Rive】Android与Rive交互
  • HCIA-Access V2.5_2_2网络通信基础_TCP/IP协议栈报文封装
  • Nginx 缓存那些事儿:原理、配置和最佳实践
  • 【数据结构——栈与队列】链栈的基本运算(头歌实践教学平台习题)【合集】
  • Docker 安装 Jenkins:2.346.3
  • 北京仰望星空大学的飞船
  • Electron electron-builder.yml 配置 (自定义包名,用户自定义安装目录...)
  • flink sink kafka的事务提交现象猜想
  • avue-crud 同时使用 column 与 group 的问题
  • 2024前端面试题(持续更新)
  • 力扣题目 - 935. 骑士拨号器
  • 【汇编】思考汇编中的两个基本问题
  • STM32F407+LAN8720A +LWIP +FreeRTOS ping通
  • c# 协变与抗变
  • 蓝桥杯我来了
  • 【1211更新】腾讯混元Hunyuan3D-1文/图生3D模型云端镜像一键运行
  • 微服务篇面试题
  • 案例讲解自然语言处理(NLP)
  • 【从零开始入门unity游戏开发之——C#篇03】变量和常量
  • SpringBoot3集成MybatisPlus3和knife4j(swagger3兼容增强版)
  • C语言,有关const
  • Prime2_解法二:openssl解密凭据
  • tcpdump编译
  • uboot移植网络驱动过程,无法ping通mx6ull和ubuntu问题解决方案
  • C++小白实习日记——Pollnet,Efvi,UDP,数据类型转换(下)
  • 【Spark】Spark性能调优