“回调函数”超难面试题!!

 1 <script>
 2     let app = {
 3         ary: [],
 4         use(fn) {
 5             this.ary.push(fn);
 6         }
 7     };
 8     app.use((next) => {
 9         console.log(1);
10         next();
11         console.log(2)
12     });
13     app.use((next) => {
14         console.log(3);
15         next();
16         console.log(4)
17     });
18     app.use((next) => {
19         console.log(5);
20         next();
21         console.log(6)
22     });
23     callBack(0);
24     function callBack(index) {
25         if (index === app.ary.length)
26             return;
27         let newAry = app.ary[index];
28         newAry(() => {
29             callBack(index + 1);
30         })
31     }
32 </script>

进来的小伙伴可以先自己思考一下

 

对于还属于小白的我来说扫了一眼这些代码的反应是:“这都是啥?”

但是我也比较喜欢钻研~ 仔细看了第二眼的反应是:“这回调函数也太回调了吧!”

又看了第三眼差不多也理解了一星半点,写出解题逻辑的同时也让自己理解的更深刻一点

 

 

答案输出:1  3  5  6  4  2;

1. 

 app.use((next) => {
     console.log(1);
     next();
     console.log(2)
     });
这一步是让对象app里属性名为use的函数执行,里面的箭头函数作为fn的形参添加到ary空数组中;
以此类推后面两个方法执行里的实参同样作为fn的形参添加到ary数组当中;


2.

callBack(0);
function callBack(index) {
    if (index === app.ary.length)
           return;
    let newAry = app.ary[index];
newAry(() => {
callBack(index + 1);
}) }
函数callback执行传参0,判断不成立继续往下,let newAry = app.ayr[index],可以看成
let newAry = (next)=>{
console.log(1);
next();
console.log(2);
};
紧接着newAry执行里面的参数()=>{callBack(index+1)} 被形参next接收,代码执行 **首先输出1**;
接下来是 next() 就等于传的参数
()=>{callBack(index+1)} 执行,里面紧接着是 函数callBack执行;
此时index的参数计算后为 1 ;判断依旧不成立,继续往下执行;按前面原理经过计算后 **分别输出 3 5 **

3.

   最后(next) => { console.log(5); next();  console.log(6) };  输出 5 之后;函数callBack执行此时里面的判断成立不再执行;

   紧接着 **输出 6 ** 由于上面的方法执行没有执行完,而且因为 newAry 执行回调函数的嵌套,所以需要再从里到外

   执行再 **分别输出 4  2 **;所以最后 答案是:1  3  5  6  4  2;



 



posted @ 2018-10-01 00:22  五迷  阅读(822)  评论(0编辑  收藏  举报