javascript - 有没有更好(更干净)的方法来使用三元运算符(不重复代码)编写这个 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 });
}
解决方案
考虑到只有三种可能的状态(赢、输、平),我们只需要检查其中的两种。平局很容易检查,所以我们只需要输赢的状态。这是一个例子:
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!" })
}
推荐阅读
- python - 使用相等变量将两个列表合并为一个
- express - Jest 集成测试 Express REST API 与 Mongoose
- android - eglCreateWindowSurface() 只能使用 Surface、SurfaceView、SurfaceTexture 或 SurfaceHolder 的实例调用
- swift - UserDefaults to Image 代码构建,但运行时崩溃
- swift - 与泛型的关联类型一致的协议会产生编译器错误
- javascript - 如何传递模式类型:对象的关键规则
- python - 简单 Python/C API 测试中的 Nullptr 错误
- php - 检查数组中的所有值是否都在数据库中并存储不在新数组中的值
- c# - 如何使用实体框架中的 DBContext 获取在另一列中具有重复数据的所有 ID?
- three.js - Three.js Mesh 从前面的对象继承颜色