如何基于一个数组选中元素的索引查找另一数组中对应的子数组
实现方案
你的questions与answers数组是按索引一一对应的关系,questions[0]对应answers[0]、questions[1]对应answers[1],以此类推。
现有代码的核心问题是用字符串类型的question值去元素全为子数组的answers中查找索引,永远无法匹配到结果,answers.indexOf(question)始终返回-1,导致答案数组操作完全错误。
直接基于随机索引同步操作两个数组即可解决问题,代码如下:
const questions = ["q1", "q2", "q3"] const answers = [ ["r", "f", "f", "f"], ["r2", "f2", "f2", "f2"], ["r3", "f3", "f3", "f3"] ]; function pickQuestion() { if (questions.length > 0) { // 生成合法随机索引 const randomIndex = Math.floor(Math.random() * questions.length); // 按索引同时取出匹配的问题和对应答案子数组 const question = questions[randomIndex]; const answerArray = answers[randomIndex]; // 同步移除两个数组对应索引的已使用元素 questions.splice(randomIndex, 1); answers.splice(randomIndex, 1); return [question, answerArray]; } else { return "End of questions"; } }
该方案不需要额外调用indexOf查找元素位置,性能更高,也规避了questions存在重复值时indexOf只能匹配到第一个元素的潜在bug。
内容的提问来源于stack exchange,提问作者adamozcz
相关产品推荐
相关产品推荐

