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

如何从object嵌套array中随机选元素并溯源其来源array

解决随机选取嵌套数组元素并追踪来源的问题

嘿,我来帮你搞定这个问题!你的核心需求是从三个分类的数组里随机挑一个答案,还要知道它来自哪个分类对吧?现在代码出问题主要是两个关键点没处理对,咱们一步步来修正:

问题根源分析

  1. 对象不能直接用length属性:你写的randomAnswers[Math.floor(Math.random()*randomAnswers.length)]里,randomAnswers是个对象,不是数组,所以randomAnswers.length会返回undefined,这直接导致randomAnswer变成undefined。
  2. 没从选中的数组里取元素:你的randomProperty函数返回的是整个分类数组(比如['yes','Absolutely',...]),而不是数组里的单个随机元素,而且也没记录这个数组对应的分类名称。

修正后的完整代码

const randomAnswers = { 
  goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'], 
  maybes: ['maybe','probably','perhaps',"honestly man, i really don't know this one"], 
  badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are you serious?'] 
};

{
const init = () => {
 console.log("initiated");
 let answer = document.querySelector('.answer');
 answer.style.opacity = 0;
 setTimeout(fixSentence,3000);
}

const fixSentence = () => {
 let a = document.querySelector('.answer');
 let think = document.querySelector('.think');
 console.log('shown');
 console.log(a.textContent);

 // 关键修正部分开始
 // 1. 获取所有答案分类的key(goodAnswers/maybes/badAnswers)
 const answerCategories = Object.keys(randomAnswers);
 // 2. 随机选一个分类
 const randomCategory = answerCategories[Math.floor(Math.random() * answerCategories.length)];
 // 3. 从选中的分类数组里随机选一个元素
 const randomElement = randomAnswers[randomCategory][Math.floor(Math.random() * randomAnswers[randomCategory].length)];
 // 关键修正部分结束

 // 现在你可以用randomCategory来判断答案来源,生成新语句
 console.log(`选中的答案:${randomElement},来自分类:${randomCategory}`);

 let splittedSentence = a.textContent.split(" ");
 console.log(splittedSentence);
 a.textContent = `${randomElement}`;
 a.style.opacity = 1;
 think.style.opacity = 0;
}
init();
}

核心改进点说明

  • 用Object.keys(randomAnswers)获取对象的所有分类名称,这样就能正确计算分类的数量,实现随机选分类。
  • 先选中分类,再从分类对应的数组里随机取元素,同时保留randomCategory变量,后续你可以根据这个变量的值(比如goodAnswers、maybes)来生成不同的新语句。
  • 彻底解决了原代码中randomAnswer返回undefined的问题,现在randomElement就是你需要的随机答案。

内容的提问来源于stack exchange,提问作者Arthur Robaeys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:10:04