首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中将三元运算中断为if和else

在javascript中将三元运算中断为if和else
EN

Stack Overflow用户
提问于 2020-12-06 23:21:21
回答 2查看 49关注 0票数 1

嘿,伙计们,我很难理解多个三元条件。下面是我的代码

代码语言:javascript
复制
<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中写这个(只是为了理解)。我知道这里的条件不会不稳定,但我只是想要得到一个清晰的了解,谢谢!

EN

回答 2

Stack Overflow用户

发布于 2020-12-06 23:34:02

直接转换为if/else的方法如下:

代码语言:javascript
复制
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} />

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

代码语言:javascript
复制
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}`} />
票数 3
EN

Stack Overflow用户

发布于 2020-12-06 23:30:07

代码语言:javascript
复制
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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65169680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档