使用三元运算符(不重复代码)编写此JS代码是否有更好(更清晰)的方法?

问题描述 投票:4回答:4

所以我正在写一个简单的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 });
        }
javascript reactjs if-statement ecmascript-6 ternary-operator
4个回答
4
投票

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

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!" })
}

3
投票

您可以将条件作为地图的一部分,因为条件永远不会更改并设置状态。

const condition = {
  "rock": {
    "paper": "You lose!",
    "sccissors": "You win!",
    "rock": "Draw!"
  },
  "paper": {
    "rock": "You win!",
    "sccissors": "You lose!",
    "paper": "Draw!"
  },
  "sccissors": {
    "rock": "You lose!",
    "paper": "You win!",
    "sccissors": "Draw!"
  }
};

function getResult(enemy, isRock, isScissors, isPaper) {
  let result = null;
  
  if (isRock) {
    result = condition['rock'][enemy];
  } else if (isPaper) {
    result = condition['paper'][enemy];
  } else if (isScissors) {
    result = condition['scissors'][enemy];
  }
  
  return result;
}

const {
  isRock, 
  isScissors,
  isPaper,
  enemy
} = this.state;


this.setState({
  result: getResult(enemy, isRock, isScissors, isPaper)
})

1
投票

我有一个有趣的方法,你可以尝试使用for循环和只有一个if语句。

您可以使用对象文字来设置每个状态的值:

const stateConditions = {
    "isRock": {
      "paper": "You lose!",
      "scissors": "You win!",
      "rock": "Draw!"
    },
    "isPaper": {
      "rock": "You win!",
      "scissors": "You lose!",
      "paper": "Draw!"
    },
    "isScissors": {
      "rock": "You lose!",
      "paper": "You win!",
      "scissors": "Draw!"
    }
  };

在上面的对象中,如果你执行了state = stateConditions ['isRock'],那么你将获得rock的相应条件

使用javascript this.state ['isRock']与this.state.isRock相同。并且您可以使用属性使用forin遍历对象中的每个属性,因此您可以执行以下操作来查找当前状态。这样你就可以循环遍历所有可能的状态,看看this.state ['somestate']是否为真:

for (let state in stateConditions) {
    if (this.state[state] === true) {
        // you found which state was true!
    }
}

最终代码:

const conditions = {
    "isRock": {
      "paper": "You lose!",
      "scissors": "You win!",
      "rock": "Draw!"
    },
    "isPaper": {
      "rock": "You win!",
      "scissors": "You lose!",
      "paper": "Draw!"
    },
    "isScissors": {
      "rock": "You lose!",
      "paper": "You win!",
      "scissors": "Draw!"
    }
  };

  for (const state in conditions) {
      // check if this is the state
      if (this.state[state]) {
          this.setState({ result: condition[state][this.state.enemy] });
          break;
      }
  }

这是一篇关于replacing switch statements with object literals的有趣文章


0
投票

对当前答案之一采取不同的调整,以减少重复:

const condition = {
  rock: {
    paper: -1,
    scissors: 1,
    rock: 0
  },
  paper: {
    paper: 0,
    scissors: -1,
    rock: 1
  },
  scissors: {
    paper: 1,
    scissors: 0,
    rock: -1
  }
};

function getResult({enemy, isRock, isScissors, isPaper}) {
  let result = null;

  if (isRock) {
    result = condition.rock[enemy];
  } else if (isPaper) {
    result = condition.paper[enemy];
  } else if (isScissors) {
    result = condition.scissors[enemy];
  }

  return result === -1 ? "You loose!" : result === 1 ? "You win!" : result === 0 ? "Draw!" : null;
}

this.setState({
  result: getResult(this.state)
});
© www.soinside.com 2019 - 2024. All rights reserved.