首页 > 解决方案 > 未捕获的 SyntaxError:意外标记:javascript 中的字符串文字。我不知道出了什么问题

问题描述

这是我的代码,一个简单的函数续集是我生成两个数字,一个给用户,一个给 PC,得分最高的人赢得游戏。Firefox 出现了 Uncaught SyntaxError: unexpected token: string literal error,我检查了我的代码,对我来说一切正常,我不知道出了什么问题并产生了该错误

// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.

//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);

console.log(userNumber);
console.log(pcNumber);

//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);

//I use this function to obtain the random number
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}

//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore (num1, num2) {
    var matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', tie!!';

    if (num1 > num2) {
        matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', congrats you've won';
    } else if (num1 < num2) {
        matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', you lost...';
    }

    return matchMessage;
}

标签: javascriptfunctionsyntax-error

解决方案


  1. +在添加带有变量的字符串时,您缺少一个加号。


    你在做什么:

    'Your number is ' + num1 ', PC number is '
    

    它应该是什么:

    'Your number is ' + num1 + ', PC number is '
    



  1. 当您在字符串中使用相同类型的引号时,您有两种方法可以更正它:


    • 使用不同的字符串,例如:

      ", congrats you've won"
      

    • \或者您可以使用, Like转义该字符串

      ', congrats you\'ve won'
      



试试这个:

// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.

//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);

console.log(userNumber);
console.log(pcNumber);

//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);

//I use this function to obtain the random number
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore(num1, num2) {
  var matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', tie!!';

  if (num1 > num2) {
    matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', congrats you\'ve won';
  } else if (num1 < num2) {
    matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', you lost...';
  }

  return matchMessage;
}


推荐阅读