不安分的引言
我是个萌新,刚刚看了循环链表,感觉这个东西有点意思,正好之前写过一个初始化多维数组的题目,灵感突然就来了,我不知道有没有其他人会这么写,反正我这么玩了一下。
一开始的解法
function createAry(initValue, ...args) {
if (args.length === 1) {
let temp = [];
temp.length = args[0];
return temp.fill(initValue);
}
return args.reduce((pre, item) => {
return createAry(pre, item);
}, initValue);
}
今晚的脑子一抽
function createCircleObj() {
let header = {
flag: 0,
handler() {//出口逻辑定义
},
};
let footer = {
res: 0,
item: 0,
handler() { },
next: header,
};
header.next = footer;
return header;
}
let circleObj = createCircleObj();
circleObj.handler = function (...args) {
if (this.flag ===args.length) {//编写出口逻辑
console.log(this.next.res)//打印结果
return
}
this.next.handler(...args);
};
circleObj.next.handler = function (...args) {//编写迭代逻辑
this.res = []
this.res.length = args[this.next.flag]
this.item = this.res.fill(this.item)
++this.next.flag
this.next.handler(...args);
};
circleObj.next.res = []//设置一个初始结果
circleObj.next.item = 'a'//设置一初始的参数
circleObj.handler(3)
对比
我写完了之后呢,觉得这个代码量直接就上来了,感觉像是把一个简单的问题给搞复杂了,不过从思维的角度上,好像所有执行的逻辑变成类似循环的操作了。
最后
2021年4月11日02:00:00 准备睡觉 晚安