element tree 获取获取对应的父级数据
node1是节点,key1是要获取数据的键值
getParentTree(node1, key1) {
let arr = JSON.parse(JSON.stringify([node1.data[key1]]));
function getParent(node) {
// 判断当前节点是否有父节点,并且父节点上的data不能是数组
if (node.parent && !Array.isArray(node.parent.data)) {
// 将父节点上data的menuid存储在 `parentlist` 里
node.parent.data instanceof Object &&
arr.push(node.parent.data[key1]);
// 递归调用 父节点上有父节点
getParent(node.parent);
}
}
getParent(node1, key1);
return arr;
},
删除级联数据中的空children
export function delateMenuChildren(arr) {
if (arr.length) {
for (let i in arr) {
if (arr[i].children.length) {
delateMenuChildren(arr[i].children);
} else {
delete arr[i].children;
}
}
}
return arr;
}
根据id找出递归数组的具体项
// tableTree递归数据
//value要找的属性值
//key 要找的属性名
findResult(tableTree, value,key) {
let result = {}
for (let index = 0; index < tableTree.length; index++) {
const element = tableTree[index];
if (element[key] == value) {
return result = element
} else if (element.children && element.children.length > 0) {
return result = this.findResult(element.children, value,key)
} else {
}
}
return result
},
时间戳转年月日 yymmddhhmmss
export function getTimeStr(timestamp) {
var date = new Date(timestamp * 1);
var YY = date.getFullYear() + '-';
var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
return YY + MM + DD +" "+hh + mm + ss;
}
时间格式转时间戳
Date.parse(1562655555)
获取当前时间 年月日时分秒
getNowTime: function() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
return timer;
},
计算倒计时
created(){
this.timer = setInterval(() => {
_this.getCountDown()
}, 1000);
},
totalTime=60*60;
getCountDown() {
let maxtime = this.totalTime;
if (this.totalTime >= 0) {
var minutes = Math.floor(this.totalTime / 60);
var seconds = Math.floor(this.totalTime % 60);
this.countDown = `${minutes}:${seconds}`;
--this.totalTime;
} else {
clearInterval(this.timer);
}
},
计算时间差
/*
*beginDate 2021-01-02
*endDate 2021-03-02
*/
function getSecondByDateSub(beginDate,endDate) {
var beginDate = new Date(beginDate);
var endDate = new Date(endDate);
var diff = endDate.getTime() - beginDate.getTime();
var sec = Math.ceil(diff / 1000 / 60);
let d = this.totalTime - sec;
return d;
}
判断中文
export function isChn(str){
var reg=/^[\u4E00-\u9FA5]+$/;
if (!reg.test(str)){
alert( "不全是中文" );
return false ;
}else{
alert( "全是中文" );
return true ;
}
}
当有正则时json.stringify 结果为空
原因
JSON.stringify会处理的几种类型: String, Number, Boolean, null, Array, Object
不会处理的几种类型: Date, RegExp, undefined, Function
解决
用到JSON.stringify方法中的第二个可选参数 replacer。
// 将正则对象转换为正则字符串
export function stringifyJson(json){
return JSON.stringify(json, (k, v) => {
if(v instanceof RegExp){
return v.toString();
}
return v;
});
}
// 将正则字符串转成正则对象
export function parseJson(jsonStr){
return JSON.parse(jsonStr, (k, v) => {
try{
if (eval(v) instanceof RegExp) {
return eval(v);
}
}catch(e){
}
return v;
});
}
带函数或正则的反序列化
export function stringifyJson(json){
return JSON.stringify(json, (k, v) => {
if(v instanceof RegExp){
return v.toString();
}
if (typeof v === 'function') {
return v + '';
}
return v;
});
}
export function parseJson(jsonStr){
return JSON.parse(jsonStr, (k, v) => {
if (v.indexOf && v.indexOf('function') > -1 ||v.indexOf && v.indexOf('=>') > -1 ) {
return eval('(function(){return ' + v + ' })()')
}
try{
if (eval(v) instanceof RegExp) {
return eval(v);
}
}catch(e){
}
return v;
});
}
找出指定的2个字符在 该字符串里面的 位置
export function subStringStr(str, strStart, strEnd) {
let strStartIndex = str.indexOf(strStart);
let strEndIndex = str.indexOf(strEnd);
if (strStartIndex < 0) {
return "";
}
if (strEndIndex < 0) {
return "";
}
/* 开始截取 */
let result = str.substring(strStartIndex, strEndIndex).substring(strStart.length);
return result;
}
将字符串对象转换成对象格式
var code2='{mode:2}'; //语句
console.log(eval('(' + code2 + ')'));
将字符串的变量转换成真正的变量
var a=8
var code2='`${a}`'; //语句
console.log(eval(code2));
滚动条固定在底部
var div = this.$refs.chat_box;
div.scrollTop = div.scrollHeight;
//vue要等dom元素渲染完之后
this.$nextTick(() => {
var div = this.$refs.chat_box;
div.scrollTop = div.scrollHeight;
});
返回文件名
let fileName = "xxx_file.png"
let last = fileName.substring(0, fileName.indexOf("."))
console.log(last) //xxx_file
获取文件后缀
let fileName = "xxx_file.png"
let fileExtension= fileName.substring(fileName.lastIndexOf('.') );
let fileExtension1= fileName.substring(fileName.lastIndexOf('.') +1); //不带点
console.log(fileExtension) // .png
console.log(fileExtension1) // png
用 set 快速找出一个数组中不重复的值的个数
let arr=[1,2,3,2,1];
let set=new Set(arr);
console.log(set.size);//3
用set快速实现数组去重
let arr =[12,5,6,12];
console.log(Array.form(new Set(arr)));//[12,5,6]
Object对象的操作
Object.keys();返回对象的键名数组
Object.values();返回对象的键值数组;
Object.entries();返回对象键名和键值的数组;
let obj = {
id: 1,
name: 'hello',
age: 18
};
console.log(Object.keys(obj)); // 输出结果: ['id', 'name', 'age']
console.log(Object.values(obj)); // 输出结果: [1, 'hello', 18]
console.log(Object.entries(obj)); // 输出结果: [['id', 1], ['name', 'hello'], ['age', 18]
promise 的 finally()方法,无论异步调用成功或失败都会执行的方法
实用场景:调接口时请求结束关闭loading 状态
promise
.then(() => console.log('success'))
.catch(() => console.log('fail'))
.finally(() => console.log('finally'))
Object.fromEntries()方法可以把键值对列表转换为一个对象。
const object = { key1: 'value1', key2: 'value2' }
const array = Object.entries(object) // [ ["key1", "value1"], ["key2", "value2"] ]
Object.fromEntries(array) // { key1: 'value1', key2: 'value2' }
有条件的向对象中添加值,有时候空值不需要加到对象中去
const condition = null;
const person = {
id: 1,
name: 'John Doe',
...(condition && { age: condition }),
};
检查属性值是否在对象中
let person={name:"王五",age:0};
console.log("name" in person)//true
获取数组对象的交集或差集
let arr1 = [{ id: 1, name: "张三"},{ id: 2, name: "李四"},{ id: 3, name: "王五"}]
let arr2 = [{ id: 1, name: "张三"},{ id: 2, name: "李四"}]
//差集
let arrDiff = [...arr1].filter(x => [...arr2].every(y => y.id !== x.id));
console.log(arrDiff) //[{id: 3,name: "王五"}]
//交集
let arrInter = [...arr1].filter(x => [...arr2].some(y => y.id === x.id));
console.log(arrInter ) //[{id: 1,name: "张三"},{id: 2,name: "李四"}]
数组对象根据id去重
let person = [{ id: 1,}, { id: 2,}, { id: 1,}, ]
let obj = {}
person = person.reduce((cur, next) => {
console.log(cur, next)
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
}, [])
console.log(person)//[{id:1},{id:2}]
生成100000-999999的随机数
function GetRandomNum(Min, Max) {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
GetRandomNum(10000, 999999)
生成具体位数的字符串
function createdBit(size) {
let list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let val = ""
for (var i = 0; i < size; ++i) {
var tmp = parseInt((list.length) * Math.random());
if (i == 7) {
if (tmp % 2 == 0) {
val += '_';
} else {
val += list[tmp] + '_';
list.splice(tmp, 1);
i++;
}
} else {
//document.write("<br />"+list.length+" == "+tmp);
val += list[tmp];
list.splice(tmp, 1);
}
}
return val
}
console.log(createdBit(16),)//ZE65uoMn_I8FXbNQ
使用“at方法”读取数组的尾元素
一般是用我们需要以“array.length-1”作为下标来读取,这里推荐一种简便的方法
let arr=[1,2,3,4,5]
console.log(arr[arr.length-1)//数组最后一位 5
console.log(arr.at(0))//数组第一位 1
console.log(arr.at(-1))//数组最后一位 5
flat递归结构一个新数组
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
// The default depth is 1
const flat1 = array.flat() // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
const flat2 = array.flat(2) // [ 1, 2, 3, [ 4, [ 5 ] ] ]
const flatAll = array.flat(Infinity) // [ 1, 2, 3, 4, 5 ]