1. 程式人生 > >“回調函數”超難面試題!!

“回調函數”超難面試題!!

代碼執行 代碼 同時 function 這一 his this push use

 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;



 



“回調函數”超難面試題!!