在 JavaScript 中返回表示数组中每种数据类型频率的映射
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 18:20:17
我们需要编写一个 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
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

