从此switch语句中执行return;或return null;是否更有意义?

对于以下功能,从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被认为是一个好习惯吗?

tanyuran 回答:从此switch语句中执行return;或return null;是否更有意义?

除了三者之一外,什么时候还需要返回什么?

如果JS引擎突然在Math中产生错误,则可能要抛出错误。

否则,只需使用随机数,该随机数将始终为3个选择中的index an array的0、1或2。注意,没有括号时,无需显式的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());

本文链接:https://www.f2er.com/3111776.html

大家都在问