如何统计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() {}的类型为functionnew Object()、[]、{}、null的typeof结果均为object,合计4次NaN、Infinity、0的typeof结果均为number,合计3次undefined的类型就是undefined
- 遍历数组时,通过统计对象记录每种类型的出现次数:若类型已存在则计数+1,不存在则初始化为1
内容的提问来源于stack exchange,提问作者Rohit Verma
相关产品推荐
相关产品推荐

