从此switch语句中执行`return'';`或`return null;`更有意义吗?

问题描述 投票:0回答:1

对于以下功能,从return ''子句中对return nulldefault有意义吗?

const getComputerChoice = () => {
  const randomNumber = Math.floor( Math.random() * 3 );

  let computerChoice;
  switch (randomNumber) {
    case 0:
      computerChoice = 'rock';
      break;
    case 1:
      computerChoice = 'paper';
      break;
    case 2:
      computerChoice = 'scissors';
      break;
    default:
      computerChoice = '';
  }

  return computerChoice; 
}    

const getComputerChoice = () => {
  const randomNumber = Math.floor( Math.random() * 3 );

  let computerChoice;
  switch (randomNumber) {
    case 0:
      computerChoice = 'rock';
      break;
    case 1:
      computerChoice = 'paper';
      break;
    case 2:
      computerChoice = 'scissors';
      break;
    default:
      computerChoice = null;
  }

  return computerChoice; 
}    

而且,即使在break子句中也包含default,这也是一个好习惯吗?

javascript null switch-statement break
1个回答
2
投票

什么时候需要返回三个之中之一以外的任何东西?

如果JS引擎突然在数学运算中发现错误,则可能会引发错误。否则,只需使用始终为0、1或2的随机数来索引3个选择的数组。注意,没有括号时,无需显式的return语句

const getComputerChoice = () => ["rock", "paper", "scissors"][Math.floor(Math.random() * 3)];

console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
console.log(getComputerChoice());
© www.soinside.com 2019 - 2024. All rights reserved.