JS报错Uncaught ReferenceError: Dolphins未定义,求原因解析
错误原因分析与修复方案
核心错误点
- 未定义标识符报错:代码开头
const teamA = Dolphins;和const teamB = Koalas;里的Dolphins、Koalas是未声明的变量,你实际想表示的是队名字符串,必须用单引号或双引号包裹,否则JS会把它们当作变量查找,找不到就抛出ReferenceError。 - 平均分计算逻辑错误:当前写法
96 + 108 + 89 / 3会先计算89/3,再和前面的数相加,这不是正确的平均分计算方式,应该把三个分数先求和再除以3,需要给加法部分加括号。 - else语句语法错误:最后一行
else (avgScoreDolphins === avgScoreKoalas); {是无效语法,else不需要额外条件,且分号会打断代码块关联,直接写else {即可。
修复后的完整代码
const teamA = 'Dolphins'; const teamB = 'Koalas'; const avgScoreDolphins = (96 + 108 + 89) / 3; console.log(avgScoreDolphins); const avgScoreKoalas = (88 + 91 + 110) / 3; console.log(avgScoreKoalas); if (avgScoreDolphins > avgScoreKoalas) { console.log(`The winning team is ${teamA}`); } else if (avgScoreKoalas > avgScoreDolphins) { console.log(`The winning team is ${teamB}`); } else { console.log(`The competition has ended in a draw between ${teamA} and ${teamB}`); }
内容的提问来源于stack exchange,提问作者Elippsis007
相关产品推荐
相关产品推荐

