对于以下功能,从return ''
子句中对return null
或default
有意义吗?
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
,这也是一个好习惯吗?
什么时候需要返回三个之中之一以外的任何东西?
如果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());