在If语句中,JavaScript函数随机返回undefined

时间:2018-01-23 18:53:12

标签: javascript function return

我正在学习JavaScript并拥有这个非常简单的应用程序,该应用程序返回数组中的随机项,但前提是它与返回的上一项不同。我的代码如下。它通常工作正常,但有时甚至在前一行的console.log返回有效项时随机返回undefined。如果我在If语句之外返回它永远不会返回undefined。

为什么我的函数有时只在If语句中返回undefined并在外面正常工作?

let ranArray = [
    "flaky","pickle","grass","juicy","desert","wonderful","even","signal","frail","team","addition"
    ];

let previousRanNum = 12;

function generateNumber (){
    return Math.floor(Math.random()*11);
};

function getItem(){

    let ranNum = generateNumber();

    if (ranNum !== previousRanNum) {
        previousRanNum = ranNum;
        console.log(ranNum);
        console.log(ranArray[ranNum]);
        return ranArray[ranNum];
    } else {
        getItem();
    }
};

调试控制台:

getItem()
undefined
10
addition

以下工作正常,永远不会返回undefined:

function getItem(){

    let ranNum = generateNumber();

    if (ranNum !== previousRanNum) {
        previousRanNum = ranNum;
        console.log(ranNum);
        console.log(ranArray[ranNum]);
    } else {
        getItem();
    }
    return ranArray[ranNum];
};

0 个答案:

没有答案