首页 > 文章列表 > 如何用JavaScript循环提取数组对象中的值?

如何用JavaScript循环提取数组对象中的值?

299 2025-04-07

如何用JavaScript循环提取数组对象中的值?

JavaScript数组对象值循环提取方法

本文介绍如何使用JavaScript循环遍历数组对象并提取所需的值。

针对特定数据结构,您可以使用以下代码:

for (const key in arr) {
  const countArray = [];
  const yearArray = [];
  for (const subkey in arr[key].lists) {
    countArray.push(arr[key].lists[subkey].count);
    yearArray.push(arr[key].lists[subkey].year);
  }
  console.log(countArray);
  console.log(yearArray);
}

这段代码将输出以下结果:

['0', '3', '2', '1']
['2020', '2021', '2022', '2023']
['1', '2', '3', '4']
['2020', '2021', '2022', '2023']
['3', '2', '3', '4']
['2020', '2021', '2022', '2023']

选择for...infor...of循环取决于您的数据结构。 根据具体情况,您可能需要调整代码以适应不同的数据结构。 例如,使用map()方法可以更简洁地实现相同的功能。

来源:1739973991