此编码问题的一些背景。我们的 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
}
}, {})
关于javascript - 在此代码中要执行的三元运算符的真值在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790631/