JavaScript 如何计算数组中的数据类型数量
给定一个数组,任务是计算用于创建该数组的数据类型的数量。
示例:
Input: [1, true, "hello", [], {}, undefined, function(){}]
Output: {
boolean: 1,
function: 1,
number: 1,
object: 2,
string: 1,
undefined: 1
}
Input: [function(){}, new Object(), [], {},
NaN, Infinity, undefined, null, 0]
Output: {
function: 1,
number: 3,
object: 4,
undefined: 1
}
方法1
在此方法中,我们使用Array.reduce()方法,并将该方法初始化为空对象。
// JavaScript program to count number of
// data types in an array
let countDtypes = (arr) => {
return arr.reduce((acc, curr) => {
// Check if the acc contains the
// type or not
if (acc[typeof curr]) {
// Increase the type with one
acc[typeof curr]++;
} else {
/* If acc not contains the type then
initialize the type with one */
acc[typeof curr] = 1
}
return acc
}, {}) // Initialize with an empty array
}
let arr = [function () { }, new Object(), [], {},
NaN, Infinity, undefined, null, 0];
console.log(countDtypes(arr));
输出
{ function: 1, object: 4, number: 3, undefined: 1 }
方法2
在这个方法中,我们使用Array.forEach()方法来迭代数组。并创建一个空数组,每次迭代时,我们检查当前迭代是否在新创建的对象中出现。如果是,则将类型加1;否则,创建一个名为类型的新键,并初始化为1。
// JavaScript program to count number of
// data types in an array
let countDtypes = (arr) => {
let obj = {}
arr.forEach((val) => {
// Check if obj contains the type or not
if (obj[typeof val]) {
// Increase the type with one
obj[typeof val]++;
} else {
// Initialize a key (type) into obj
obj[typeof val] = 1;
}
})
return obj
}
let arr = [function () { }, new Object(), [], {},
NaN, Infinity, undefined, null, 0
];
console.log(countDtypes(arr));
输出
{ function: 1, object: 4, number: 3, undefined: 1 }
极客教程