You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于一个数组选中元素的索引查找另一数组中对应的子数组

实现方案

你的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:06:04