gpt4 book ai didi

JavaScript 错误 :Uncaught SyntaxError: Unexpected identifier

转载 作者:行者123 更新时间:2023-11-28 17:51:33 30 4
gpt4 key购买 nike

我是 javascript 编码的初学者,当我在 Chrome 浏览器中加载第一个程序时遇到此错误,请教我它是什么

代码:

 var target;
var select;
var colors = ["brown", "cyan", "yellow", "red", "blue", "green", "black", "white", "purple", "pink"];
var finished = false;

function do_game() {
var random_color = Math.floor(Math.random() * colors.length);
target = colors[random_color];
}
while (!finished) {
select = prompt("I am thinking of one of these colors\n\n brown,cyan,yellow,red,blue,green,black,white,purple,pink\n what color am i thinking of");
finished = check_guess();
}

function check_guess() {
if (select == target) {
return true;
} else {
return false;
}

}

最佳答案

您提到的实际错误不会出现在您提供的代码中。我假设您在 HTML 属性中调用了 do_game ,例如 onclick 属性,并且那里有一个小拼写错误,例如放错位置的逗号或使用保留字, ...或许多其他语法问题之一。

你应该:

  • 调用 do_game(您提供的代码中从未调用过它)
  • 将循环放入该函数中

并进一步改进:

  • 检测用户何时取消提示
  • 使用局部变量而不是全局变量,并在其他地方需要时通过函数参数传递变量。真正的常量可以是全局的。
  • 使用 letconst 而不是 var
  • 避免使用 if(比较)return true else return false 模式。只需进行返回比较即可。
  • 让用户知道他们猜对了
  • 由于您已经有了一个颜色数组,因此不要在问题中再次将其作为文字字符串重复,而是重复使用该数组。

// The list of colors can be global, but the rest should be locally defined
const colors = ["brown", "cyan", "yellow", "red", "blue", "green", "black", "white", "purple", "pink"];

function do_game() {
const random_color = Math.floor(Math.random() * colors.length);
// Make your variables local to the function
const target = colors[random_color];
let finished = false;

while (!finished) {
// Actually declare `select`, or it will be global.
// Reuse the variable with colors to build the question
// (the commas will be inserted by the automatic conversion to string)
const select = prompt("I am thinking of one of these colors\n\n"
+ colors + ".\n\n What color am I thinking of?");
// Exit game when prompt was cancelled
if (select === null) return;
// Pass the necessary info to the other function (instead of using globals):
finished = check_guess(select, target);
}
// Let the user know that they guessed it
alert('You guessed it: ' + target);
}

function check_guess(select, target) {
// No need to if-else a true/false, just return the comparison's result
return select == target;
}

// Start the game
do_game();

关于JavaScript 错误 :Uncaught SyntaxError: Unexpected identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45431428/

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