首页 > 解决方案 > JS 函数记录答案但返回“未定义”

问题描述

我正在尝试在 vanilla JS 中的二维数组中进行查找。

    ["fruit","apple","orange","grape","banana","peach"],
    ["veg", "cucumber", "carrot", "eggplant","lettuce","tomato","cabbage","bean"],
    ["flower", "rose", "carnation", "orchid"],
    ["color", "red","green","blue","cyan","yellow","magenta","black","white"],
    ["aircraft","monoplane","biplane","helicopter","hot air balloon", "gas balloon","autogyro","airship","sailplane","powerlift"]
];

let mytopic = "color";

const choose = topic => {
    choices.forEach(row => {
        if (row[0] == topic) {
            var index = Math.floor(Math.random() * (row.length - 1)) + 1;
            console.log(row[index]);
            return row[index];
        }
    });
};

alert(choose(mytopic));

预期的答案出现在控制台中,但警报始终显示“未定义”。

我知道这一定很简单,但是在这里和 MDN 上搜索了一个小时后,我完全感到困惑。

...是的,我知道番茄真的是一种水果。

标签: javascriptfunctionmultidimensional-array

解决方案


Your return statement is for your inner function starting with row =>, which won't do anything. forEach doesn't return anything by design, and your function itself has no return statement either.

One way to rewrite this is to find the row and then work with it. You can't short circuit a forEach with a return statement, it will still execute for every element in the array.

const choose = topic => {
    const row = choices.find(row => row[0] == topic);
    const index = Math.floor(Math.random() * (row.length - 1)) + 1;
    console.log(row[index]);
    return row[index];
};

推荐阅读