在此 switch 语句中执行 `return '';` 或 `return null;` 是否更有意义?
Does it make more sense to do `return '';` or `return null;` from within this switch statement?
对于以下函数,default
子句中的 return ''
或 return null
更有意义吗?
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;
}
此外,即使在 default
子句中也包含 break
是否被认为是一个好习惯?
这什么时候需要 return 除了三者之一之外的任何东西?
如果JS引擎在Math中突然出现bug,你可能会想抛出一个错误。
否则只需使用始终为 0、1 或 2 的随机数到 index an array 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());
对于以下函数,default
子句中的 return ''
或 return null
更有意义吗?
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;
}
此外,即使在 default
子句中也包含 break
是否被认为是一个好习惯?
这什么时候需要 return 除了三者之一之外的任何东西?
如果JS引擎在Math中突然出现bug,你可能会想抛出一个错误。
否则只需使用始终为 0、1 或 2 的随机数到 index an array 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());