抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

Mr.wang

Time flies and people come and go

记录开发中的使用 js 减少重复操作的优良代码

生成有序数组

1
2
3
4
orderedArray=(n)=>[...new Array(n).keys()] 
orderedArray(10) //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9
orderedArray(6).map(i=>i+4) //[4, 5, 6, 7, 8, 9]
orderedArray(6).map(i=>(i+1)*4)//[4, 8, 12, 16, 20, 24]

计算对象+=每个值得长度

中英文都计算为一个字符长度

1
2
3
4
5
6
7
8
9
10
11
12
13
let test = { a: "hhh", dd: "ddd", e: { f: "哈哈哈" } };
let length = 0;
stringLength = (val) => {
for (const key in val) {
if (typeof val[key] == "object") {
stringLength(val[key]);
} else {
length += val[key].length;
}
}
};
stringLength(test);
console.log(length);

对象转为 table 显示的树状带 children 结构(可能带 bug)

data 测试数据集合

1
2
3
4
5
6
7
module.exports = {
a: 1,
b: {
c: 2
},
d: [{ e: 5 }]
};

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const data = require("./data.js");
let emun = {id:'',describe:'',must:"是"}
let keyWord = 'filed'
let strType = 'type'
let typeEmun = {
'number':'NUMBER',
'string':'STRING',
'boolean':'BOOLEAN',
'object':'LIST OBJECT'
}
let count = 0
let output = []
function coverData(data,output){
for(let d in data){
if(typeof data[d] !='object'){
output.push(yuansu(d,data[d]))
}else{
let temp = yuansu(d,data[d])
temp.children=[]
let index = output.push(temp)
if(data[d] instanceof Array &&data[d].length==1){
coverData(data[d][0],output[index-1]['children'])
}else{
coverData(data[d],output[index-1]['children'])
}
}
}
}
function yuansu(d,data){
count++;
emun.id = count
let temp = JSON.parse(JSON.stringify(emun))
temp[keyWord] = d
temp[strType] = typeEmun[typeof data]
return temp
}
coverData(data,output)
console.log(JSON.stringify(output))

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[
{ id: 1, describe: "", must: "是", filed: "a", type: "NUMBER" },
{
id: 2,
describe: "",
must: "是",
filed: "b",
type: "LIST OBJECT",
children: [{ id: 3, describe: "", must: "是", filed: "c", type: "NUMBER" }]
},
{
id: 4,
describe: "",
must: "是",
filed: "d",
type: "LIST OBJECT",
children: [{ id: 5, describe: "", must: "是", filed: "e", type: "NUMBER" }]
}
];

评论