Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

怎么理解这个返回值?

var time = 0; var res = "";
var a = function () {
    time++;
    if (time < 5) {
        res = a();
    }else{
        return 1;
    }
    console.log(res);
    return "end"+time
};
a();
// 下面是执行结果
1
end5
end5
end5
"end5"

为什么先打印1呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你这是个递归函数,在time<5之前要递归调用4次a(),当time===5时,递归结束return 1;递归结束是从里往外进行返回,所以第一个打印出来的是1。而time是个全局变量,所以最后都是5。
你可以这样改一下看的更清楚:

var time = 0; var res = "";
var a = function () {
    time++;
    let current = time;
    if (time < 5) {
        res = a();
    }else{
        return 1;
    }
    console.log(res,current);
    return "end"+current;
};
a();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...