问题描述
const getUserChoice = (userInput=userInput.toLowerCase()) => {
if (userInput==='rock'||userInput==='paper'||userInput==='scissors') {
return userInput;
}
else {
console.log('Error!');
}
};
console.log(getUserChoice('Scissors'));
//这似乎不起作用。仅当我输入所有小写字母的单词时。
解决方法
const getUserChoice = (userInput) => {
userInput = userInput.toLowerCase()
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput;
} else {
return 'Error!'; //changed to return
}
};
,
const getUserChoice = (userInput=userInput.toLowerCase()) => {
在这一行中,您将创建函数参数的默认值,除非范围内存在undefined
,否则它将为userInput
。它不会操纵您传递的参数。
例如这样的功能:
const hello = (name="stranger") => console.log(`hello,${name}`)
如果不带参数调用,将说“你好,陌生人”,如果叫hello("Scrissors")
,则说“你好,剪刀”。
当您调用函数:getUserChoice('Scissors')
时,默认参数将被传递的内容覆盖,而函数内的userInput
为"Scissors"
。
您需要在函数体内进行转换:
const getUserChoice = (userInput) => {
userInput=userInput.toLowerCase()
/* now userInput is the lowercase version of the argument you pass */
}
,
您可以尝试
const getUserChoice = (Input) => {
let userInput = Input.toLowerCase();
if (userInput==='rock' || userInput==='paper' || userInput==='scissors') {
return userInput;
} else {
console.log('Error!');
}
};
console.log(getUserChoice('Scissors'));