【问题标题】:Where is the truthy value for the ternary operator to execute upon in this code?在此代码中执行三元运算符的真实值在哪里?
【发布时间】:2019-11-10 16:27:14
【问题描述】:

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

我无法理解的是扩展运算符,以及它如何为三元运算符创建一个真实的语句来操作。

【问题讨论】:

  • 三元是acc[cv] ? acc[cv]+1 : 1...acc 在其他属性中传播,[cv]: 是计算属性名称。

标签: javascript shortcut conditional-operator spread


【解决方案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
    }
  }, {})

【讨论】:

    【解决方案2】:

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

    1. 整个条件运算符表达式为acc[cv] ? acc[cv]+1 : 1,因此根据acc[cv] 是否为真,它只会解析为acc[cv]+11
    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;
    }
    

    【讨论】:

      【解决方案3】:

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

      acc[cv] 是一个计算属性,它将查找cv 的值作为acc 的属性,例如acc['smart city']

      【讨论】:

        猜你喜欢
        • 2017-01-01
        • 2020-12-18
        • 1970-01-01
        • 2017-12-06
        • 2020-08-27
        • 2021-03-09
        • 1970-01-01
        • 2011-07-08
        • 2021-11-16
        相关资源
        最近更新 更多