【问题标题】:Breaking ternary operations to if, else in javascript在javascript中将三元操作分解为if,else
【发布时间】:2020-12-06 15:21:21
【问题描述】:

大家好,我很难理解多个三元条件。下面是我的代码

<div
            className={
              this.state.currentIndex == index
                ? "question-box bg-red-box"
                : question.visited
                ? question.review
                  ? "question-box review-box"
                  : question.selected_answer == null
                  ? "question-box white-box"
                  : "question-box orange-box"
                : "question-box"
            }
          >

if else 我怎么写这个(只是为了理解)。我知道这里的条件不会不稳定,但我只是想让它在其他情况下得到一个清晰的理解 谢谢!

【问题讨论】:

    标签: javascript conditional-operator


    【解决方案1】:

    if/else 的直接翻译是:

    let temp;
    if (this.state.currentIndex == index) {
      temp = "question-box bg-red-box"
    } else {
      if (question.visited) {
        if (question.review) {
          temp = "question-box review-box";
        } else {
          if (question.selected_answer == null) {
            temp = "question-box white-box"
          } else {
            temp = "question-box orange-box"
          }
        }
      } else {
        temp = "question-box"
      }
    }
    
    // later:
    <div className={temp} />
    

    这两个版本的代码都不容易理解。我可能会做类似以下的事情:

    let highlight = '';
    if (this.state.currentIndex === index) {
      highlight = "bg-red-box";
    } else if (question.visited && question.review) {
      highlight = "review-box";
    } else if (question.visited && question.selected_answer === null) {
      highlight = "white-box";
    } else if (question.visited) {
      highlight = "orange-box";
    }
    
    // ...
    <div className={`question-box ${highlight}`} />
    

    【讨论】:

      【解决方案2】:

      let currentIndex = 1;
      
      let index = 2;
      
      let question = {
          visited: true,
          review: false,
          selected_answer: null
      }
      
      let output = '';
      
      
      if(currentIndex == index){
          output = 'question-box bg-red-box'
      } else if (question.visited) {
          if(question.review){
              output =  "question-box review-box"
          } else if (question.selected_answer == null) {
              output =  "question-box white-box"
          } else {
              output =  "question-box orange-box"
          }
      } else {
          output =  "question-box"
      }
      
      console.log(output)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多