JavaScript switch语句出现Unexpected identifier错误排查
问题分析:Uncaught SyntaxError: Unexpected identifier 'state'
你的代码如下:
$(() => { 'use strict'; const updateLabels = countryEl => { const selectedCountry = countryEl.value; var state = ''; switch(selectedCountry){ case 'JP': state = 'Prefecture'; break; case 'CA': state = 'Province'; break; case 'US' state = 'State'; break; } <do other stuff> }; });
浏览器抛出错误:
address.js:15 Uncaught SyntaxError: Unexpected identifier 'state'
错误根源并非state变量未定义,而是switch语句中case 'US'的后面缺少了冒号:。JavaScript语法要求每个case标签后必须跟随冒号,你的代码破坏了这一语法结构,导致浏览器无法正确解析后续代码,进而抛出看似和state相关的错误——实际上是语法解析中断后,浏览器误判了后续代码的合法性。
修复后的代码:
$(() => { 'use strict'; const updateLabels = countryEl => { const selectedCountry = countryEl.value; var state = ''; switch(selectedCountry){ case 'JP': state = 'Prefecture'; break; case 'CA': state = 'Province'; break; case 'US': // 补上缺失的冒号 state = 'State'; break; } // do other stuff }; });
这类语法错误属于"解析中断型错误",报错信息常指向错误位置附近的变量,但核心问题是前面的语法结构不完整。排查时重点检查switch的每个case是否都符合case 取值:的格式即可。
内容的提问来源于stack exchange,提问作者Cerin
相关产品推荐
相关产品推荐

