gpt4 book ai didi

javascript - 我的剪刀石头布脚本无法运行。控制台日志 : Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

转载 作者:行者123 更新时间:2023-12-02 22:07:35 26 4
gpt4 key购买 nike

我刚刚开始学习javaScript,我的第一个项目是制作一个在控制台上玩的剪刀石头布游戏,我编写的代码是:

<!DOCTYPE html>
<html>
<body>
<script>

let RPS = function playRound (playerSelection, computerSelection) {

let playerSelection = promt ("What do you choose?", "");

let computerSelection = math.Random ();
if computerSelection (<0.34) {
computerSelection = "Rock";
} else if computerSelection (>=0.35 && <=0.66) {
computerSelection = "Paper";
} else {
computerSelection = "Scissors";
}

if (playerSelection === "Rock"){
if (computerSelection === "Scissors") {
console.log ("You win");
} else {
console.log ("You lose");
}
}
if (playerSelection === "Paper") {
if (computerSelection === "Scissors"){
console.log ("You win");
}else {
console.log ("You lose")
}
}
if (playerSelection === "Scissors") {
if (computerSelection ==== "Paper"){
console.log ("You win")
} else {
console.log ("You lose")
}
}

}

</script>
</body>
</html>

当我尝试在控制台上运行它时,我得到

Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

这是为什么?

最佳答案

这个错误非常简单。您传递名为 playerSelectioncomputerSelection 的参数,然后立即尝试声明两个同名的局部变量 - 但是,参数本身被视为局部变量,因此您确实在重复。要么将变量作为参数传递给函数,要么使用 let 在代码中声明它们,但不能同时使用两者。

此外,您的代码充满了语法错误,您绝对需要校对此代码,因为即使您解决了问题中提出的问题,它也不会运行。

以下是您可能想要的示例:

let RPS = function playRound() {
let playerSelection = prompt("What do you choose?", "");
let computerSelection = Math.random();

if (computerSelection < 0.34) {
computerSelection = "Rock";
} else if (computerSelection >= 0.35 && computerSelection <= 0.66) {
computerSelection = "Paper";
} else {
computerSelection = "Scissors";
}

if (playerSelection === "Rock") {
if (computerSelection === "Scissors") {
console.log("You win");
} else {
console.log("You lose");
}
}
if (playerSelection === "Paper") {
if (computerSelection === "Scissors") {
console.log("You win");
} else {
console.log("You lose")
}
}
if (playerSelection === "Scissors") {
if (computerSelection === "Paper") {
console.log("You win")
} else {
console.log("You lose")
}
}
}

RPS()

关于javascript - 我的剪刀石头布脚本无法运行。控制台日志 : Uncaught SyntaxError: Identifier 'playerSelection' has already been declared,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com