一、要求
// Write a function that takes an array of numbers as argument
// Convert the array to an object
// It should have a key for each unique value of the array
// The corresponding object value should be the number of times the key occurs within the array
二、解
function myFunction(a) {
return a.reduce((acc, cur) => {
return { ...acc, [cur]: acc[cur] + 1 || 1 };
}, {})
}
还可以通过遍历数组,然后依次将数组的值作为对象的属性,然后通过计算次数,但是远不如reduce优雅。