常用计算库:https://mikemcl.github.io/decimal.js/#toFixed
/**
* 把树型数据的node组成一个数组
* @param node
*/
static getTreeNodeArr(node: any, tempArr: Array<any>) {
tempArr.push(node);
if (node && node.parent && node.parent.children) {
// 简化结构(解决无限递归parent)
let chilArr = node.parent.children;
for (let k = 0; k < chilArr.length; k++) {
const eleChil = chilArr[k];
eleChil.parent = {};
}
node.parent.children = [];
}
if (node && node.children && node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
const element = node.children[i];
this.getTreeNodeArr(element, tempArr);
}
}
return tempArr;
}
static toJson(str: any) {
try {
if (str && typeof str === 'string') {
return JSON.parse(str);
} else {
console.log(typeof str, 'troJson error');
}
} catch (error) {
console.log(error);
}
}
static simpleDeepClone(initalObj: object) {
return Utils.toJson(JSON.stringify(initalObj));
}
// 拷贝对象数组
static copyObjArray(fromItem) {
let toItem = [];
for (let obj of fromItem) {
let newObj = {};
for (let key of Object.keys(obj)) {
newObj[key] = obj[key];
}
toItem.push(newObj);
}
return toItem;
}
/**
* 拷贝对象 将fromObj的属性值copy到toObj中(toObj中没有对应的值才拷贝,有的话就不拷贝)
* 用于修改和添加对象时候的对象赋值
*/
static copyObj(toObj, fromObj) {
console.log(Object.keys(fromObj));
for (let key of Object.keys(fromObj)) {
if (fromObj.hasOwnProperty(key) && fromObj[key]) {
toObj[key] = fromObj[key];
}
}
return toObj;
}
/**
* 拷贝对象 将fromObj的所有属性值copy到toObj中
*
*/
static copyObjAll(toObj, fromObj) {
console.log(Object.keys(fromObj));
for (let key of Object.keys(fromObj)) {
toObj[key] = fromObj[key];
}
return toObj;
}
static deepClone(initalObj) {
let obj = {};
for (let key in initalObj) {
if (initalObj.hasOwnProperty(key)) {
let prop = initalObj[key];
// 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
if (prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[key] = (prop.constructor === Array) ? [] : Object.create(prop);
} else {
obj[key] = prop;
}
}
}
return obj;
}
网友评论