如何用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
相关产品推荐
相关产品推荐

