JavaScript 错误 :Uncaught SyntaxError: Unexpected identifier

标签 javascript

我是 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/

相关文章:

javascript - react 路由器中的链接未定义错误

javascript - 复选框状态更改不起作用

javascript - React js如何从组件外部发布axios

javascript - 在 webkit 浏览器中通过 Javascript 使用 CSS 重新绘制减速

javascript - IE 中的下拉列表没有变化

javascript - <label><label/> 标记内的 <A><A/> 标记在 href 上具有 javascript 函数无法运行

javascript - 如何将 Dialogflow v2 与 javascript 前端 (Vue.js) 集成

javascript - 通过 json 实时搜索以查看给定字符串是否在数组中

javascript - jquery 模式弹出窗口中的按键

Javascript 将变量传递给输入元素中的内联函数