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

如何在Javascript中循环获取数组内对象的值?

在JavaScript中循环获取数组内部对象的值的几种方法

嘿,我来帮你解决这个问题!你提供的是一个包含Windows系统版本信息的数组,咱们可以用多种JavaScript的循环方式来获取每个对象里的name和version_id值,下面是具体的实现方法:

首先先把你的数据源明确下来(补全了截断的最后一个对象):

const data = {
  "versions": [
    { "name":"Windows 8.1 with Update 3 (build 9600)", "version_id":"11" },
    { "name":"Windows 7 SP1 (build 7601)", "version_id":"9" },
    { "name":"Windows 10, Version 1803 - Redstone 4 [Apr 2018] (build 17134.1)", "version_id":"97" },
    { "name":"Windows 10, Version 1709 - Redstone 3 [Sep 2017] (build 16299.15)", "version_id":"92" },
    { "name":"Windows 10, Version 1703 - Redstone 2 [March 2017] (build 15063.0)", "version_id":"41" },
    { "name":"Windows 10, Version 1607 - Redstone 1 [Aug 2016] (build 14393.0)", "version_id":"34" }
  ]
};

1. 基础的for循环

这是最传统的循环方式,兼容性拉满,适合需要手动控制循环进度(比如中途跳出、跳过)的场景:

const versions = data.versions;
for (let i = 0; i < versions.length; i++) {
  const currentVersion = versions[i];
  console.log(`系统名称:${currentVersion.name},版本ID:${currentVersion.version_id}`);
}

2. forEach数组迭代方法

写法简洁直观,是日常遍历数组的常用选择,不需要手动管理索引:

data.versions.forEach(currentVersion => {
  console.log(`系统名称:${currentVersion.name},版本ID:${currentVersion.version_id}`);
});

如果需要用到当前元素的索引,还可以添加索引参数:

data.versions.forEach((currentVersion, index) => {
  console.log(`第${index + 1}个版本:${currentVersion.name},版本ID:${currentVersion.version_id}`);
});

3. for...of循环(ES6+)

语法更贴近自然语言,支持break、continue这类循环控制语句,兼顾简洁性和灵活性:

for (const currentVersion of data.versions) {
  console.log(`系统名称:${currentVersion.name},版本ID:${currentVersion.version_id}`);
}

4. 提取特定字段到新数组(map方法)

如果你不需要遍历输出,而是想把所有对象的某个字段提取出来形成新数组,map会是最优选择:

// 提取所有系统名称到新数组
const allVersionNames = data.versions.map(item => item.name);
console.log(allVersionNames);

// 提取所有版本ID到新数组
const allVersionIds = data.versions.map(item => item.version_id);
console.log(allVersionIds);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:14:02