tip:空值合并运算符(??)是一个逻辑运算符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。in 如果指定的属性在指定的对象或其原型链中,则 in 运算符返回 true。 const countedNames = ["red", "red", "green", "yellow", "pink","red","pink","red"].reduce((allNames, cur) => {const currCount = allNames[cur] ?? 0;return {...allNames,[cur]: currCount + 1,};}, {});console.log(countedNames); let arr = ["red", "red", "green", "yellow", "pink","red","pink","red"].reduce( (allNames, cur)=> {if (cur in allNames) {allNames[cur]++;} else {allNames[cur] = 1;}return allNames;}, {}); console.log(arr);