JavaScript代码报Uncaught SyntaxError(意外字符串字面量),排查无果
语法报错定位与修复
当前代码触发Uncaught SyntaxError: unexpected token: string literal的原因有三个,任意一个问题都足以让解析器抛出该错误:
- 字符串拼接漏写连接符:所有拼接数字变量和提示文本的位置,数字和后续字符串之间没有写
+运算符,比如初始定义结果信息的语句'Your number is ' + num1 ', PC number is ',num1和后面的字符串字面量之间没有连接逻辑,解析器读到字符串时会判定为意外标记。平局、用户赢、PC赢三个分支的拼接逻辑全部存在这个问题。 - 字符串引号冲突:外层用单引号包裹的字符串内容里包含了单引号撇号,比如
'congrats you've won'里you've的单引号会被JS识别为字符串提前闭合,剩下的ve won'就成了完全无效的语法片段。 - 无效转义内容:代码里的
>、<是HTML场景下的大于、小于符号转义形式,不能直接作为JS的比较运算符使用,需要替换回原生的>、<。
修复后可直接运行的代码
// 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; }
对应改动说明
- 给所有数字变量和后续字符串的拼接位置补上缺失的
+连接符 - 将包含单引号撇号的赢局提示字符串外层替换为双引号,避免引号提前闭合的冲突
- 把HTML转义的比较符号替换为JS原生的大于、小于运算符
内容的提问来源于stack exchange,提问作者Alebacce
相关产品推荐
相关产品推荐

