此编码问题的某些背景。我们的termTopics函数需要统计调查中每个主题被提及的次数,然后以以下顺序返回一个数组,其中包含被提及的数量:智慧城市,艺术资助以及交通。
const termTopics = (interviews) => {
const count = interviews.reduce((acc, cv) => {
return {...acc, [cv]: acc[cv] ? acc[cv]+1 : 1}
}, {})
return [count['smart city'], count['arts funding'], count['transportation']];
}
我无法理解的是散布运算符,以及它如何为三元运算符创建一个真实的声明。
const count = interviews
.reduce((resultObject, interview) => {
// We are creating an object through the reduce function by iterating through the interviews array.
// At each iteration we will modify the result object according to the current array interview item value
return {
// First we copy the object we have so far
...resultObject,
// Then we set the property corresponding to the current item
[interview]: resultObject[interview]
// If it is not the first time we have seen this item, the object property already exists and we update it by adding one to its value
? resultObject[interview] + 1
// Otherwise we create a new property and set it to one
: 1
}
}, {})
真值(或虚假)值来自这里:acc[cv]
,如果有一个值,则将其递增一,否则将其设置为一。
acc[cv]
是计算属性,并将cv
的值查找为acc
的属性,例如acc['smart city']
。
扩展语法和条件运算符在这里完全无关。让我们在这里来回展开:
acc[cv] ? acc[cv]+1 : 1
,因此根据acc[cv]+1
是否为真,它将仅解析为1
或acc[cv]
。[cv]
-等于computed property name当前值的cv
。...acc
,或者对象的当前值为spread into the object。实际上,{...acc, [cv]: acc[cv] ? acc[cv]+1 : 1}
是以下ES5代码的缩写:
var result = {};
//{...acc}
for (var key in acc) {
result[key] = acc[key];
}
//[cv]: acc[cv] ? acc[cv]+1 : 1
if (acc[cv]) {
result[cv] = acc[cv]+1;
} else {
result[cv] = 1;
}