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

标签 javascript shortcut conditional-operator spread

此编码问题的一些背景。我们的 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/

相关文章:

javascript - ESLint eslint-plugin-react 箭头函数

eclipse - Eclipse 中添加注释代码的快捷按钮

python - 如何用 Pythonese 说 - 做某事,除非它导致错误(不诉诸多级 try/execpt block )

javascript - 预期是赋值或函数调用,但看到的是三元表达式

eclipse - 如何将 Intellij IDEA 键盘映射导入 Eclipse?

swift - Bool 的简洁 Swift 断言? || bool ?

javascript - javascript中的自定义排序功能不起作用

javascript - filterDescendants 和 findDescendant 与 slate.js

javascript - 如何对齐工具提示的中心

shortcut - 如何使用 Google Drive API 创建快捷方式?