JS无论首行内容如何均抛出location重复声明语法错误求助
问题解决:Uncaught SyntaxError: Identifier 'location' has already been declared
核心原因
location 是浏览器全局对象 window 的内置属性(用于获取/设置当前页面URL等信息),属于JavaScript的预定义全局标识符,不能用 const、let 或 var 重新声明。你的代码中使用 const location = ... 尝试重定义这个全局变量,直接触发语法错误。
解决方案
将变量名修改为非全局保留的名称,比如 locationEl:
//Any first Line const timeEl = document.getElementById("time"); const dateEl = document.getElementById("date"); const currentInfoEl = document.getElementById("current-info"); const timeZone = document.getElementById("time-zone"); // 修改变量名避免全局标识符冲突 const locationEl = document.getElementById("location"); const forecast = document.getElementById("forecast"); const currentTempEl = document.getElementById("current-info");
错误指向首行的额外处理
你提到仅运行 console.log("hello"); 仍报错指向首行,大概率是浏览器缓存了旧的错误代码,可通过以下方式解决:
- 按
Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面,清除缓存 - 打开开发者工具(F12),在「设置」中勾选「禁用缓存」(刷新页面时生效)
- 检查HTML是否引入了其他包含
const location的JS文件,排查跨脚本变量冲突
内容的提问来源于stack exchange,提问作者Kill Hell
相关产品推荐
相关产品推荐

