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

如何将同类型数据存入数组?如何为游戏对象genre字段设多值?

如何在游戏对象中存储多个游戏类型?

在JavaScript对象里,重复的属性名会被最后一个赋值覆盖,所以你之前写三次genre的写法,只会保留最后一个值'Survival'。

要存储多个游戏类型,只需要把genre字段改成数组类型,把所有类型作为数组元素放入即可,修改后的代码如下:

{
  name: "The Last of Us",
  console: 'PS3',
  genre: ['Horror', 'Stealth', 'Survival']
}

如果是包含多款游戏的数组,完整结构可以这样写:

const games = [
  {
    name: "The Last of Us",
    console: 'PS3',
    genre: ['Horror', 'Stealth', 'Survival']
  },
  {
    name: "Zelda: Breath of the Wild",
    console: 'Switch',
    genre: ['Action-Adventure', 'Open World']
  }
];

后续要访问或遍历游戏类型也很方便,比如获取第一款游戏的所有类型并打印:

games[0].genre.forEach(genre => {
  console.log(genre);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:02