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

如何统计JavaScript数组中各数据类型的出现次数?

数组数据类型统计实现方案

你当前的代码只是把数组转成了以索引为键的对象,无法实现类型统计需求,按以下方式修改即可得到目标结果:

实现代码

const arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];
const typeCount = {};

arr.forEach(item => {
  const type = typeof item;
  typeCount[type] = (typeCount[type] || 0) + 1;
});

console.log('OutPut:', typeCount);

运行结果

OutPut: { function: 1, object: 4, number: 3, undefined: 1 }

关键说明

  • 用typeof获取每个元素的类型,刚好匹配你需要的统计规则:
    • function() {}的类型为function
    • new Object()、[]、{}、null的typeof结果均为object,合计4次
    • NaN、Infinity、0的typeof结果均为number,合计3次
    • undefined的类型就是undefined
  • 遍历数组时,通过统计对象记录每种类型的出现次数:若类型已存在则计数+1,不存在则初始化为1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:10:26