记录下经常用的的js方法:
//比较时间
const time1 = "20223-04-20 09:00:00";
const time2 = "2023-04-20 09:00:01";
const overtime = time1 < time2;
//console.log(overtime) true
//金额格式化
const ThousandNum = num => num.toString().replace(/\B(?=(\d{2})+(?!\d))/g, ",");
const money = ThousandNum(1000000);
console.log(money)
//生成随机id
const RandomId = len => Math.random().toString(36).substr(3, len);
const id = RandomId(8);
console.log(id) //4v6nycoc
//+号的妙用 转化为数字或者时间戳
const num1 = +null; //0
const num2 = +""; //0
const num3 = +false; //0
const num4 = +"169"; //169
const timestamp = +new Date("2023-04-20"); //时间戳
//十进制数字
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.2345, 2);
// num => 1.23
//判断奇数偶数
const OddEven = num => !!(num & 1) ? "odd" : "even";
const num = OddEven(2);
//判断数据的类型
function DataType(tgt, type) {
const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
return type ? dataType === type : dataType;
}
DataType("test"); // "string"
DataType(20220314); // "number"
DataType(true); // "boolean"
DataType([], "array"); // true
DataType({}, "array"); // false
//判断数组是否为空
const arr = [];
const flag = Array.isArray(arr) && !arr.length;
//判断对象不为空
const obj = {a: 0, b: 1, c: 2};
Object.keys(obj).length>0
//数组转化为对象
const arr = [0, 1, 1, 2, 2, 2];
const count = arr.reduce((t, v) => {
t[v] = t[v] ? ++t[v] : 1;
return t;
}, {});
// count => { 0: 1, 1: 2, 2: 3 }