计算数组中数据类型的数量-JavaScript
我们需要编写一个JavaScript函数,该函数接受一个数组,该数组包含不同数据类型的元素,并且该函数应返回一个表示每种数据类型的频率的映射。
假设以下是我们的数组-
const arr = [23, 'df', undefined, null, 12, {
name: 'Rajesh'
}, [2, 4, 7], 'dfd', null, Symbol('*'), 8];示例
以下是代码-
const arr = [23, 'df', undefined, null, 12, {
name: 'Rajesh'},
[2, 4, 7], 'dfd', null, Symbol('*'), 8];
const countDataTypes = arr => {
return arr.reduce((acc, val) => {
const dataType = typeof val;
if(acc.has(dataType)){
acc.set(dataType, acc.get(dataType)+1);
}else{
acc.set(dataType, 1);
};
return acc;
}, new Map());
};
console.log(countDataTypes(arr));输出结果
以下是控制台中的输出-
Map(5) {
'number' => 3,
'string' => 2,
'undefined' => 1,
'object' => 4,
'symbol' => 1
}热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短