在此代码中三元运算符要执行的真实值在哪里?

问题描述 投票:0回答:3

此编码问题的某些背景。我们的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']];
}

我无法理解的是散布运算符,以及它如何为三元运算符创建一个真实的声明。

javascript shortcut conditional-operator spread
3个回答
1
投票
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
    }
  }, {})

0
投票

真值(或虚假)值来自这里:acc[cv],如果有一个值,则将其递增一,否则将其设置为一。

acc[cv]计算属性,并将cv的值查找为acc的属性,例如acc['smart city']


0
投票

扩展语法和条件运算符在这里完全无关。让我们在这里来回展开:

  1. 整个条件运算符表达式为acc[cv] ? acc[cv]+1 : 1,因此根据acc[cv]+1是否为真,它将仅解析为1acc[cv]
  2. 条件运算符的结果被分配给对象中的属性。
  3. 属性名称为[cv]-等于computed property name当前值的cv
  4. 属性名称和值添加到对象。
  5. 其余的对象值为...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;
}
© www.soinside.com 2019 - 2024. All rights reserved.