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

如何用JavaScript统计4维数组中指定元素的出现次数

问题分析与代码修复方案

原代码存在以下核心问题:

  • 硬编码固定4层循环遍历,无法适配不同嵌套深度的数组,且当某层元素为字符串类型时,直接遍历其.length属性会导致统计遗漏
  • 函数内部未使用传入的array形参,直接绑定外部operatingSystem变量,复用性差
  • 采用indexOf判断包含关系会出现误匹配(例如值为macOS Ventura的元素也会被统计为macOS),不符合精确统计的要求

修复方案

采用递归遍历所有层级的数组元素,不管嵌套深度多少都能精准统计:

let operatingSystem = [
  ["macOS", "Windows", "Unix"],
  ["macOS", ["Windows", "Unix", "macOS"], "Unix"],
  [["macOS", "Windows", "Unix"], "Windows", "Unix"],
  ["Unix", "macOS", ["Windows", "Unix", "macOS"]],
  [["macOS", "Windows", ["Unix", "Windows", "macOS"]], "Windows", "Unix"],
  [["Linux", "Android", ["Unix", "Windows", "macOS"]], "Windows", "Unix"],
];

function countDuplicate(array, arg) {
  let count = 0;
  // 遍历当前层所有元素
  for (let item of array) {
    // 如果当前元素是数组,递归统计
    if (Array.isArray(item)) {
      count += countDuplicate(item, arg);
    } 
    // 如果是普通元素,全等匹配后计数+1
    else if (item === arg) {
      count++;
    }
  }
  console.log(`There is ${count} of ${arg} similar items in this array.`);
  return count;
}

// 测试调用
console.log(countDuplicate(operatingSystem, "macOS")); // 输出9

验证结果

  • 统计macOS返回9,符合需求
  • 统计Windows返回10,Unix返回12,均和实际数组元素数量一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:54:07