var myVar;在 Chrome 中返回 HTMLDivElement 但在 FF 中不返回?
我尝试在脚本的第一行设置一个变量,以便稍后可以访问它(并检查它是否未定义。代码的基本要点是:
var map;
var mapIsVisible = false;
console.log(map);
function clearMap() {
if(map != undefined) {
map.clear();
}
}
clearMap();
所以在 FF 中,它工作得很好。没有任何错误。Chrome 抛出错误提示:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'clear'
这导致我在变量实例化后执行 console.log,并且得到的是 HTMLDivElement。为什么 FF 返回未定义,而 Chrome 却说它是 HTMLDivElement,而它显然不是?对于您声明的没有任何类型的所有变量,
我现在的解决方法是明确指出映射未定义:
var map = undefined;
并且我想知道为什么 Chrome 会发生这种情况
编辑 。 正如答案中所说,我确实有一个 id 为“map”的元素。我不知道他们会自动添加 JS 变量。
I tried to set a variable in the very first line of my script so I could access it later(and check if it was undefined. The basic gist of the code is:
var map;
var mapIsVisible = false;
console.log(map);
function clearMap() {
if(map != undefined) {
map.clear();
}
}
clearMap();
So in FF, it works perfectly. No errors whatsoever. Chrome throws an error that says:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'clear'
which led me to do that console.log after the variable instantiation and what I got was an HTMLDivElement. Why is it that FF returns undefined while Chrome says its an HTMLDivElement when it clearly isn't? Or does chrome set that to all variables you declare that don't have any type to them?
My fix for now was to explicitly say that map was undefined:
var map = undefined;
and my script works well. What I want to know is why this happens for Chrome
EDIT
As said in the answers, I DO have an element with an id of "map". I didn't know that they automatically added JS variables for that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的页面上的某处可能有一个
,并且 chrome 认为您正在使用您使用的“map”变量引用它。
You might have a
<div id="map">
on your page somewhere and chrome thinks you are referencing it with the "map" variable you use.我的猜测是,您的页面上有一个
name
或id
属性为“map”的元素。我似乎记得 id-ed 元素在 Chrome 中自动成为全局 JS 变量。天知道为什么。My guess is that you have an element on your page with a
name
orid
attribute of "map." I seem to recall id-ed elements automatically becoming global JS variables in Chrome. God knows why.