分享一些工作上经常会用到的js片段
// 1.快速计算累加(纯数字数组)
const numberArray = [1, 2, 3, 4];
const sum = numberArray.reduce((p, v) => p + v, 0);
console.log(sum); // 10
// 2.快速计算对象数组累加值
const objArray = [{ a: 3 }, { a: 2 }, { a: 3 }, { a: 4 }];
const obj_sum = objArray.reduce((p, v) => p + v.a, 0);
console.log(obj_sum); // 12
// 3.数组标识转对象映射
const data = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
];
const dic = data.reduce((p, v) => ({ ...p, [v.id]: v }), {});
console.log(dic); // { '1': { id: 1, name: 'a' }, '2': { id: 2, name: 'b' } }
// 4.利用反射减少if的一行对象赋值方式
let where = { a: 1 };
where.a == 1 && Reflect.set(where, "b", 2);
console.log(where); // {a:1,b:2}
// 5.set去重
let repeatArray = [1, 2, 3, 1, 4, 2];
console.log([...new Set(repeatArray)]); // [ 1, 2, 3, 4 ]
// 6.安全删除数组项
let index = numberArray.find((x) => x == 1);
index != -1 && numberArray.splice(index, 1);
// 7.数组位置交换
let temp = [0, 1];
[temp[0], temp[1]] = [temp[1], temp[0]];
console.log(temp); // [ 1, 0 ]
// 8.深拷贝对象
let copy = JSON.parse(JSON.stringify(obj_sum));
// 9.扁平化树型结构 适用于vxe-table树型结构
const tree = [{ id: 1, name: "father", children: [{ id: 2, name: "son", children: [{ id: 3, name: "grandSon" }] }] }];
const flat = (nodes, dic, parentId) => {
for (let node of nodes) {
node.children && node.children.length && flat(node.children, dic, node.id);
dic[node.id] = { ...node, parentId };
}
return dic;
};
const treeDic = flat(tree, {});
// {
// '1': { id: 1, name: 'father', children: [ [Object] ] },
// '2': { id: 2, name: 'son', children: [ [Object] ] },
// '3': { id: 3, name: 'grandSon' }
// }
console.log(treeDic);
// 10.扁平化树型结构恢复 适用于vxe-table的数据转回element-table使用
const restore = (flatObj) => {
const result = [];
const map = {};
for (let id in flatObj) {
map[id] = { ...flatObj[id], children: [] };
}
for (let id in map) {
const node = map[id];
if (node.parentId) {
map[node.parentId].children.push(node);
} else {
result.push(node);
}
}
return result;
};
const restoredTree = restore(flat(tree, {}));
// [{"id":1,"name":"father","children":[{"id":2,"name":"son","children":[{"id":3,"name":"grandSon","parentId":2,"children":[]}],"parentId":1}]}]
console.log(JSON.stringify(restoredTree));
// 11.快速合并数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
// [ 1, 2, 3, 4, 5, 6 ]
console.log(mergedArray);
// 12.统计对象数组每个对象的属性值累加情况 有唯一标识的情况下 常用于echarts数据展示需求
const moenyTable = [
{ user_id: "a", money: 10 },
{ user_id: "b", money: 20 },
{ user_id: "c", money: 30 },
{ user_id: "a", money: 40 },
].reduce((p, v) => {
p[v.user_id] = (p[v.user_id] || 0) + v.money;
return p;
}, {});
// { a: 50, b: 20, c: 30 }
console.log(moenyTable);
// 13.获取文件的类型后缀
const getFileType = (fileName) => {
let index = fileName.lastIndexOf(".");
return index != -1 ? fileName.substring(index + 1) : "";
};
console.log(getFileType("txt123.txt")); // txt
// 14.需要手动传页数的pagination组件 手动计算分页 向上取整解决缺少页数的问题
const pageSize = 3;
let source = {
rows: [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
],
total: 4,
};
let pageCount = Math.ceil(source.total / pageSize);
console.log(pageCount, source.total / pageSize); // 2 1.3333333333333333
// 15.随机数[a,b]
const randomFrom = (lowerValue, upperValue) => {
return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
};
console.log(randomFrom(0, 100)); // 0-100区间的随机数
// 16.增加原型链上的方法 快捷数字类型保证上限
Number.prototype.getLower = function (min, max) {
return Math.min(this, randomFrom(min, max));
};
let n = { b: 50 };
console.log(n.b.getLower(0, 100)); // 0-100区间的随机数