JS函数记录答案,但返回“未定义”

时间:2019-08-23 20:40:45

标签: javascript function multidimensional-array

我正在尝试在香草JS中的2d数组中进行查找。

    ["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上搜索了一个小时之后,我完全困惑了。

...是的,我知道西红柿确实是一种水果。

1 个答案:

答案 0 :(得分:0)

您的return语句用于以row =>开头的内部函数,该函数不会执行任何操作。 forEach在设计上不会返回任何内容,您的函数本身也没有return语句。

一种重写方法是找到该行,然后对其进行处理。您无法使用forEach语句使return短路,它仍将对数组中的每个元素执行。

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];
};