首页 > 解决方案 > 有没有更好(更干净)的方法来使用三元运算符(不重复代码)编写这个 JS 代码?

问题描述

所以我正在写一个简单的 React.js 应用程序,只是有一个关于设置状态的问题,这可以做得更干净吗?

const enemy = this.state.enemy;
        if (this.state.isRock) {
            enemy === "rock"
                ? this.setState({ result: "Draw!" })
                : enemy === "paper"
                ? this.setState({ result: "You lose!" })
                : enemy === "scissors"
                ? this.setState({ result: "You win!" })
                : this.setState({ result: null });
        } else if (this.state.isPaper) {
            enemy === "rock"
                ? this.setState({ result: "You win!" })
                : enemy === "paper"
                ? this.setState({ result: "Draw!" })
                : enemy === "scissors"
                ? this.setState({ result: "You lose!" })
                : this.setState({ result: null });
        } else if (this.state.isScissors) {
            enemy === "rock"
                ? this.setState({ result: "You lose!" })
                : enemy === "paper"
                ? this.setState({ result: "You win!" })
                : enemy === "scissors"
                ? this.setState({ result: "Draw!" })
                : this.setState({ result: null });
        }

标签: javascriptreactjsif-statementecmascript-6ternary-operator

解决方案


考虑到只有三种可能的状态(赢、输、平),我们只需要检查其中的两种。平局很容易检查,所以我们只需要输赢的状态。这是一个例子:

const enemy = this.state.enemy;
let wins = {
    "rock"     : "scissors",
    "paper"    : "rock" ,
    "scissors" : "paper",
}
let play = (this.state.isRock ? "rock" : (
  this.state.isPaper ? "paper" : (
    this.state.isScissors ? "scissors" : null
    )
  )
)

if (!wins[play]) {
    this.setState({ result: null })
} else if (enemy == play) {
    this.setState({ result: "Draw!" })
} else if (wins[play] == enemy) {
    this.setState({ result: "You win!" })
} else {
    this.setState({ result: "You lose!" })
}

推荐阅读