我在codecademy上使用基本的岩石剪刀纸游戏。我不明白一步。
const getUserChoice = function (userInput) {
console.log(userInput)
userInput = userInput.toLowerCase();
if ((userInput === 'paper') || userInput === 'scissors' || userInput === 'rock') {
return userInput;
} else {
console.log('Wrong user input')
}
}
为什么当我把其他东西作为参数然后字符串它不起作用?
获得用户选择('AAA')它的效果很好,但它不适用于getUser Choice(aa)。有人可以向我解释一下吗?
当你尝试运行getUserChoice ('AAA')
时,你试图将'AAA'
传递给函数。 'AAA'
是一个字符串(以单引号开头和结尾的字符),因此该函数有效。
当你尝试运行getUserChoice (aa)
时,你试图将aa
传递给函数。在这种情况下,aa
不会以'
开头和结尾,所以它不是一个字符串。在这种情况下,JavaScript假定aa
是一个变量。现在,如果未定义aa
变量,那么您将收到错误。
如果你运行var aa = 'some string';
然后运行getUserChoice (aa)
,它不会导致错误。
简而言之,您的aa
变量未定义,这就是您收到错误的原因。
它与getUserChoice('AAA')
一起工作很好,但它不与getUserChoice (aa)
合作。
'AAA'
是string
,因为它包裹在''
内。 aa
指的是一个名为aa
的变量。
如果未定义aa
,则会抛出错误。
未捕获的ReferenceError:未定义
aa
如果aa
有一个值,但它不是string
,它仍然会抛出错误,因为你在函数中调用字符串方法toLowerCase()
。
“Uncaught TypeError:
userInput.toLowerCase
不是function
”
要解决此问题,请在调用userInput
之前将string
转换为toLowerCase
。使用String()
更改类型。
let aa = 3;
const getUserChoice = function (userInput) {
userInput = String(userInput).toLowerCase();
if ((userInput === 'paper') || userInput === 'scissors' || userInput === 'rock') {
console.log("correct");
return userInput;
} else {
console.log('Wrong user input')
}
}
getUserChoice(aa)
getUserChoice(function(){console.log('sss')})
getUserChoice(55232.3323)
getUserChoice(undefined)
getUserChoice(true)
getUserChoice('paper');
原因是aa
是一个变量,但是如果你给它分配一个字符串就行了。
也没有使用toLowerCase()
。它将在一个字符串上工作,但如果你给aa
这样的let aa = 1
分配一个数字,那就不行了。不是这里1被指定为数字而不是字符串,其中aa='1'
将是一个字符串
let aa = 'AAA'
const getUserChoice = function(userInput) {
console.log(userInput)
userInput = userInput.toLowerCase();
if ((userInput === 'paper') || userInput === 'scissors' || userInput === 'rock') {
return userInput;
} else {
console.log('Wrong user input')
}
}
getUserChoice(aa)