为什么我的函数返回未定义? JS

Why is my function returning undefined? JS

我对 javascript 有点菜鸟,但我似乎找不到返回的原因 "undefined"

mineOre(userData.pickaxe, playerData.questid);

    var newOre = new function () {
        var chance = Math.floor(Math.random() * 100);
        //console.log(chance);
        /*
        20% Iron
        30% Coal
        5% Diamond
        3% Emerald
        1% Brandons Hair
        41% Stone
        */
        if (chance < 20) {
            return "Iron";
        } else if (chance < 50) {
            return "Coal";
        } else if (chance < 55) {
            return "Diamond";
        } else if (chance < 58) {
            return "Emerald";
        } else if (chance < 59) {
            return "BrandonsHair";
        } else return "Stone";
    }


    function mineOre(pickaxe, questid) {
        console.log(newOre);
    }

您在 初始化变量 newOre 之前调用 mineOre() 。如果将 mineOre() 调用移到初始化之后,您会看到 newOre 是一个空对象。它是一个对象而不是这些字符串之一,因为您的代码使用 new.

调用该匿名函数

如果您想让 newOre 成为这些字符串之一,请去掉 new 并在函数 } 结束后添加括号:

 var newOre = function () {
    var chance = Math.floor(Math.random() * 100);
    //console.log(chance);
    /*
    20% Iron
    30% Coal
    5% Diamond
    3% Emerald
    1% Brandons Hair
    41% Stone
    */
    if (chance < 20) {
        return "Iron";
    } else if (chance < 50) {
        return "Coal";
    } else if (chance < 55) {
        return "Diamond";
    } else if (chance < 58) {
        return "Emerald";
    } else if (chance < 59) {
        return "BrandonsHair";
    } else return "Stone";
}();