You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript模板字面量报Uncaught syntax error unexpected identifier问题排查

问题描述

Visual Studio Code截图,请查看图片
正在跟随Udemy教程学习编程,练习模板字面量(template literals)用法时遇到报错,需要排查代码问题,原代码如下:

const firstName = 'Greg';
const myjob = 'web developer';
const birthYear = 1991;
const currentYear = 2037;


const newSentence = "I'm " + firstName + ', a ' + (currentYear - birthYear) + ' year 
old ' + myjob + '!';
console.log(newSentence);

const gregNew = 'I\'m ${ firstName }, a ${ currentYear - birthYear} year old ${ myJob 
 } !';

console.log(gregNew);

问题排查&修正

你的代码存在3个语法错误:

  • 模板字面量必须用反引号包裹,你现在使用单引号包裹,内部的${}`插值语法不会被识别,只会被当成普通字符串内容输出。
  • 变量名大小写不匹配:你声明的变量是全小写的myjob,但在模板中调用的是首字母大写的myJob,JavaScript对大小写敏感,调用未声明的变量会触发引用报错。
  • 普通单/双引号字符串不支持直接跨行书写,你写的普通拼接字符串newSentence直接拆成了两行,会触发语法错误。

修正后的代码如下:

const firstName = 'Greg';
const myjob = 'web developer';
const birthYear = 1991;
const currentYear = 2037;

// 普通字符串拼接写法修正换行问题
const newSentence = "I'm " + firstName + ', a ' + (currentYear - birthYear) + ' year old ' + myjob + '!';
console.log(newSentence);

// 模板字面量改用反引号包裹,修正变量名大小写
const gregNew = `I'm ${ firstName }, a ${ currentYear - birthYear} year old ${ myjob } !`;
console.log(gregNew);

内容的提问来源于stack exchange,提问作者student_learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:15:08