Internet Explorer:“未定义控制台"错误 [英] Internet Explorer: "console is not defined" Error

查看:35
本文介绍了Internet Explorer:“未定义控制台"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我编写的一些 JavaScript 中使用了 console.log() 并且在 Internet Explorer 中抛出了一个错误:console is not defined(在其他浏览器中工作正常).

I was using console.log() in some JavaScript I wrote and an error of: console is not defined was thrown in Internet Explorer (worked fine in other browsers).

我已将其替换为:

if (console) console.log("...");

如果 consoleundefined,我希望条件评估为 false.因此,语句 console.log 不会被执行,也不应该抛出错误.

If console is undefined, I would expect the condition to evaluate as false. Ergo, the statement console.log wouldn't be executed and shouldn't throw an error.

相反,会抛出以下错误:console is not defined at character 4.

Instead, an error of: console is not defined at character 4 is thrown.

这是 IE 错误吗?还是如果"条件真的不合法?这似乎很荒谬,因为如果 if (console) 是非法的,那么 if (console==undefined) 也应该是非法的.

Is this a IE bug? Or is that "if" condition really illegal? It seems absurd because if if (console) is illegal, then if (console==undefined) should be illegal too.

你应该如何检查 undefined 变量?

How are you supposed to check for undefined variables?

推荐答案

如果 console 本身 根本不存在,它会抛出错误,因为您正在访问一个未定义的变量.就像 if(abc) {} 抛出错误一样.

If console itself doesn't exist at all, it throws an error because you're accessing an undefined variable. Just like if(abc) {} throws an error.

由于 console 驻留在 window 中,并且 window 确实 始终存在,所以这应该有效:

Since console resides in window, and window does always exist, this should work:

if(window.console) ...

基本上,访问不存在的属性是免费的并且不会抛出错误(它只是评估为undefinedif条件).但是,访问未声明的变量是非法的.

Basically, accessing an property that doesn't exist is free and doesn't throw an error (it just evaluates to undefined, failing the if condition). However, it is illegal to access an undeclared variable.

这篇关于Internet Explorer:“未定义控制台"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆