为什么我的返回值没有定义

Why does my return value become undefined?

本文关键字:定义 返回值 我的 为什么      更新时间:2023-09-26

我有这个函数:

function getStartDate(dateToTest) {
    var dateToUse;
    // The function here doesn't matter.  I get the same result even if I use "if (1 != 1)".
    if (!isAcceptableDate(dateToTest)) {
       dateToTest = dateToTest.addDays(1);
       getStartDate(dateToTest);
    }
    else {
        dateToUse = dateToTest;
        // It's not undefined here.......
        console.log(dateToUse);
       return dateToUse;
    }
}

在该函数末尾的console.log中,dateToUse的值是好的。然而,当它到达这个函数时,它突然变得没有定义:

function getDates(startDate) {
    console.log(startDate);
    // Do a bunch of other stuff.
}

我是这样调用这些东西的:

var baseDate = new Date();
var adjustDate = getStartDate(baseDate);
var dateArray = getDates(adjustDate);

为什么在一个函数结束时具有完全有效值的变量在被另一个函数调用时失去其值?

getStartDate函数前添加返回关键字

     return getStartDate(dateToTest);