javascript - 使用 if 语句声明 const 的值

标签 javascript constants

我有一个 const numberOfComments 是一个数组的大小,我想有另一个 const riskByComments 如果 numberOfComments 大于 2,则值为 5,否则应为 0。

我知道我可以使用 let 轻松做到这一点,但我知道最好只使用 const

    export const calculateRisk = (ticket) => dispatch => {
      const numberOfComments = ticket.comments.length
      let riskByComments//if i use const i need to declare its value
         //right away, i cannot use an if statement to do it later
      if(ticket.comments.length>2){
        riskByComments=5//if i use const inside the if statement
      }else{
         riskByComments=0//i cannot use it in the rest of my function
       }

最佳答案

使用条件运算符:

const riskByComments = numberOfComments >2 ? 5 : 0;

关于javascript - 使用 if 语句声明 const 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57072275/

相关文章:

javascript - 使用 JQuery 取消选择/取消焦点输入字段

javascript - 在浏览器窗口未处于事件状态的情况下监听 keydown 事件

go - 使用 os.Getenv 在 golang 中声明常量导致 'const initializer in os.Getenv("MY_SECRET") 不是常量'

c++ - 在初始化列表中初始化一个常量大小的数组

javascript - 使用 JavaScript 对 HTML 表格进行排序

javascript - 如何在数组中正确使用map()?

c++ - 一道C++面试题的疑惑

c - 返回 C 中静态常量变量的地址

c++ - map 的开始迭代器不起作用 C++

javascript - 选择div内ul的id