[TOC]
### 1. 获取相差时间/运行时间
~~~
const getTime = () => {
const date1 = '2021/09/16 00:00:00'; // 开始时间
const date2 = new Date(); // 结束时间
const date3 = date2.getTime() - new Date(date1).getTime(); // 时间差的毫秒数
// 计算出相差天数
const days = Math.floor(date3 / (24 * 3600 * 1000));
// 计算出小时数
const leave1 = date3 % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
const hours = Math.floor(leave1 / (3600 * 1000));
// 计算相差分钟数
const leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
const minutes = Math.floor(leave2 / (60 * 1000));
// 计算相差秒数
const leave3 = leave2 % (60 * 1000); // 计算分钟数后剩余的毫秒数
const seconds = Math.round(leave3 / 1000);
const temp = { days, hours, minutes, seconds };
return temp;
};
~~~
### 2. 数据合并统计
~~~
getChartData(value) {
if (!Array.isArray(value)) return [];
const fruitTotal = []; // 最终数据结果
const nameContainer = {};
value.forEach(item => {
let tempData =moment(item.gmt_create).format('YYYY-MM-DD');
nameContainer[tempData] = nameContainer[tempData] || [];
nameContainer[tempData].push(item);
});
const fruitName = Object.keys(nameContainer);
fruitName.forEach(nameItem => {
let count = nameContainer[nameItem].length;
fruitTotal.push({ Data: nameItem, sales: count });
});
return fruitTotal.sort((a,b)=>a.Data.split('-')[2]-b.Data.split('-')[2]);
}
var fruits =
[{
name: 'apple',
value: 1
},
{
name: 'apple',
value: 2
}, // 总计3个苹果
{
name: 'banana',
value: 2
},
{
name: 'banana',
value: 3
}]; // 总计5个香蕉
var fruitTotal = []; // 存最终数据结果
// 数据按照水果名称进行归类
var nameContainer = {}; // 针对键name进行归类的容器
fruits.forEach(item => {
nameContainer[item.name] = nameContainer[item.name] || [];
nameContainer[item.name].push(item);
});
console.log(nameContainer); // 按照水果名称归类完成:{ apple: Array(2), banana: Array(2) }
// 统计不同种类水果的数量
var fruitName = Object.keys(nameContainer); // 获取水果种类:["apple", "banana"]
fruitName.forEach(nameItem => {
let count = 0;
nameContainer[nameItem].forEach(item => {
count += item.value; // 遍历每种水果中包含的条目计算总数
});
fruitTotal.push({'name': nameItem, 'total': count});
});
console.log(fruitTotal);
// 输出结果:
// [{ name: "apple", total: 3 },
// { name: "banana", total: 5 }]
~~~
### 3. 更新url
~~~
import qs from '@alipay/bigfish/util/query-string';
// 更新 url
export function updateLocation(searchData: {}) {
const searchDataTemp = searchData;
const newQsParams = {
...qs.parse(location.search.replace('?', '')),
search: Object.keys(searchDataTemp)
.map(item => {
if (!searchDataTemp[item] || !searchDataTemp[item].length) {
delete searchDataTemp[item];
return;
}
return `${item},${searchDataTemp[item]}`;
})
.join('|'),
};
history.replaceState(null, '', `${location.pathname}?${qs.stringify(newQsParams)}`);
}
useEffect(() => {
const search = qs.parse(location.search.replace('?', '')).search as any || 'name';
const searchData = {};
let newSearch = [];
// search=a,1|b,2&search=c,3
if (Array.isArray(search)) {
newSearch = lodashFlatten(search.map(item => item.split('|')));
} else if (search) {
newSearch = search.split('|');
}
newSearch.forEach(item => {
const obj = item.split(',');
if (obj[0] && obj[1]) {
// 处理tags 这种 search=tags,1,2 case
searchData[obj[0]] = item.substr(obj[0].length + 1);
}
});
if (searchData.value) {
searchData.value = searchData.value.split(',').filter(Boolean);
}
}, [])
~~~
#### 数字格式化(金钱,分割)
~~~
329472343.1415926.toLocaleString('en-US')
// '329,472,343.142'
~~~
### 文件格式转换
#### 1、file-----二进制文件
~~~
/**
* file => base64
* @param {*} file
*/
export function asyncFileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = (e) => {
// target.result 该属性表示目标对象的DataURL
resolve(e.target.result)
}
})
}
/**
* imageFile => base64
* @param {*} file
*/
export function asyncImage2Base64(file) {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = file
img.onload = function() {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
var dataURL = canvas.toDataURL('image/' + ext)
resolve(dataURL)
// console.log(11,dataURL)
}
})
}
~~~
#### 2、二进制-----转文件
~~~
/**
* 二进制转文件
* @param {*} blobs blob对象
* @param {*} fileName 文件名
*/
export function blob2File(blobs, fileName) {
const blob = new Blob([blobs])
const href = window.URL.createObjectURL(blob) // 创建下载的链接
const aEle = document.createElement('a') // 创建a标签
aEle.href = href
aEle.download = fileName // 下载后文件名
document.body.appendChild(aEle)
aEle.click() // 点击下载
document.body.removeChild(aEle) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
}
~~~
#### 3、base64-----二进制
~~~
/**
* 将base64编码转换为二进制文件
* @param {*} base64
*/
export function base642File(base64) {
const arr = base64.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
~~~
### 4、 对象数组去重
~~~
[参考](https://www.lodashjs.com/docs/lodash.uniqWith)
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
~~~~
### 5 、 raact多次setState合并
~~~
import ReactDOM from "react-dom";
ReactDOM.unstable_batchedUpdates(() => {
// 仅仅加了unstable_batchedUpdates
// 这里的两个setState会合并执行一次。
setNum(2);
setStr('c');
});
~~~
### 6。 循环调用promis
~~~
const processUrlList = (
await Promise.all(
needProcessList?.map(async (v: any) => {
const processRes = await TableAntdApi.getProcessUrl({
id: v.id,
});
const { success, data } = processRes || {};
if (success && data) {
return {
id: v.id,
processUrl: data,
};
}
return null;
}),
)
)?.filter(Boolean);
~~~
### 7 useEffect监听对象(自定义hooks)
~~~
import React, { useEffect, useRef } from 'react';
export function useDeepCompareMemoize(value) {
const ref = useRef(value)
if (!_.isEqual(value, ref.current)) {
ref.current = value
}
return ref.current
}
const useDeepCompareEffect = (callback, dependencies)=> {
return useEffect(callback, useDeepCompareMemoize(dependencies))
}
export default useDeepCompareEffect
~~~