javascript - 未捕获的 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;
}
解决方案
+
在添加带有变量的字符串时,您缺少一个加号。
你在做什么:
'Your number is ' + num1 ', PC number is '
它应该是什么:
'Your number is ' + num1 + ', PC number is '
当您在字符串中使用相同类型的引号时,您有两种方法可以更正它:
使用不同的字符串,例如:
", 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;
}
推荐阅读
- c# - 从 C# 中缺少键的列表创建完整集
- powershell - 按时间跨度将文件过滤到单个表中
- npm - 如何强制 npm publish 包含文件(条目不需要)?
- c++ - 尝试在 C++ 中生成素数时 GMP 中的链接错误
- verilog - systemverilog 中具有真实数据类型的 inout 端口
- python - 在烧瓶中从一个应用程序调用一个变量到另一个应用程序
- mysql - MySQL 是否能够优化: where `indexed_field` IN (
)? - sql - 在 Racket 中将 SQL 查询作为惰性流处理
- vim - 用于语法突出显示的语法是什么?
- android - 如何确定 Android 手机上是否有多个用户?