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

如何从对象数组中随机获取对象并在标签模板字面量中展示?

解决方法:从对象数组展示随机对象

你当前的代码已经正确生成了随机对象,但最后渲染时错误地遍历了整个数组,导致输出所有对象。只需要调整渲染逻辑,直接使用获取到的随机对象即可:

修改后的JavaScript代码

const archetypes = [
  {
    type: 'The Magician',
    desc: 'A powerful figure who has harnessed the ways of the universe to achieve key goals.',
    strengths: 'omniscience, omnipotence, discipline',
    weaknesses: 'corruptibility, arrogance',
  }, {
    type: 'The Lover',
    desc: 'The romantic lead who’s guided by the heart.',
    strengths: 'humanism, passion, conviction',
    weaknesses: 'naivete, irrationality'
  }
];

const archetypesTemplate = types => {
  return `
    <h3><span><i>${types.type}</i></span></h3>
    <p class="desc">${types.desc}</p>
    <h3><span><u>Strengths:</u> ${types.strengths}</span></h3>
    <h3><span><u>Weaknesses:</u> ${types.weaknesses}</span></h3>  
  `;
}

const randomArchetypeGenerator = () => {
  let randomArchetype = archetypes[Math.floor(Math.random() * archetypes.length)];
  // 直接将随机对象传入模板函数,而非遍历整个数组
  document.getElementById('archetype').innerHTML = archetypesTemplate(randomArchetype);
}

randomArchetypeGenerator();

HTML代码(无需修改)

<h3>Archetype: <br><div id="archetype"></div></h3>

关键修改点

  • 移除了archetypes.map(archetypesTemplate).join('<hr>'),改为直接调用archetypesTemplate(randomArchetype),这样只会渲染随机选中的那一个对象。
  • 每次调用randomArchetypeGenerator()都会重新生成一个随机对象并渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:16:13