javascript - 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 上搜索了一个小时后,我完全感到困惑。
...是的,我知道番茄真的是一种水果。
解决方案
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];
};
推荐阅读
- python - 来自两个(立体)摄像机的连续视频流的 3D 点云
- python - Django 模型当前链接未指向 MEDIA_ROOT 中的文件
- kubernetes - k8s webhook服务的最佳实践
- java - Java Synth XML:按钮样式属性不起作用
- php - Laravel/Lumen:处理 Model::With('Relation') 的 fetchresults
- javascript - 每个请求嵌套 Js 新的 HttpService
- php - 在 Phalcon 的模型中调用 $this
- python - python解析文本文件中的条件多行
- r - 以非交互方式将反斜杠转换为 R 中的正斜杠
- python - 以动态方式将 Anaconda 链接到 Github?