js函数中关于fn()和return fn()的一个问题

var i = 0;

function fn(){

    i++;

    if(i < 10){

        fn();

    }else{

        return i;

    }

}


var result = fn();

console.log(result);

想不通为什么这里fn()不加return ,i自加到10,不走else,return的是undefined而不是10,我知道加了递归调用的时候加了return fn()就可以返回10,但是不能理解


明月笑刀无情
浏览 1026回答 1
1回答

DIEA

var i = 0;function fn(){&nbsp; &nbsp; i++;&nbsp; &nbsp; if(i < 10){&nbsp; &nbsp; &nbsp; &nbsp; //不管什么代码,递归还是其他的,我不关心,它造个原子弹也行&nbsp; &nbsp; &nbsp; &nbsp; fn()&nbsp; &nbsp; &nbsp; &nbsp; //没有返回值吧?所以返回undefined&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; //后面的递归你不去想,第一次的fn并不会进入这个分支&nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; }}var result = fn();console.log(result);小兄弟你不要被递归绕晕了,你不要管什么递归,它就是一个函数,在第一个fn进入的i<10分支里,没有返回值,那么这个函数就返回默认的undefined我们这里减少一下递归层数,手把手的一层层展开var i = 0;function fn(){&nbsp; &nbsp; i++; // 1&nbsp; &nbsp; if(i < 2){&nbsp; &nbsp; &nbsp; &nbsp; //fn()代码直接写进去&nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++ // 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i < 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ... //不会进入&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i // 貌似这里有返回值, 但是这里是这个函数的返回值,不是上面fn的返回值,而且你并没有使用这个返回值&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript